2016-08-03 53 views
-4

我很好奇,以前是否有人这样做过。如何从C中的结构中获取字符串?

我遇到了从结构中获取字符串的问题。我想要做的是从我正在使用的特定结构中获取字符串,然后将该字符串放入fprintf(“%s”,whateverstring)中;

FILE* outfile = fopen("Z:\\NH\\instructions.txt","wb"); 
if ((dir = opendir ("Z:\\NH\\sqltesting\\")) != NULL) {// open directory and if it exists 

     while ((ent = readdir (dir)) != NULL) { //while the directory isn't null 
       printf("%s\n", ent->d_name); //I can do THIS okay 

       fprintf("%s\n",ent->d_name); //but I can't do this 

        fclose(outfile); 

             } 

        } 
         closedir (dir); 

       //else { 
       // 
        //   perror (""); //print error and panic 
         //  return EXIT_FAILURE; 
        //} 
      } 

我在这里采取了错误的做法?我以某种方式考虑使用类似char[80] =ent.d_name; 但显然不起作用。有什么方法可以从结构中获取该字符串并将其放入fprintf中?

+3

heh?你读过手册页吗? –

+0

另外,没有关于结构的信息。 – sjsam

+3

['fprintf()'](http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html)不会将格式字符串作为第一个参数。 – dhke

回答

0

假设

char dname[some_number]; 

和结构对象

ent //is not a pointer 

fprintf(outfile,"%s\n",ent.d_name); // you missed the FILE* at the beginning 

ent是一个指针,那么上面的语句将变为

fprintf(outfile,"%s\n",ent->d_name); // note the -> 
1

fprintf手册页函数声明为:

int fprintf(FILE *stream, const char *format, ...); 

您不包括第一个参数。下面是一个简单的程序,证明你可以将目录的内容写入文件:

#include <stdio.h> 
#include <sys/types.h> 
#include <dirent.h> 

int main (void) 
{ 
    FILE *outfile; 
    DIR *dir; 
    struct dirent *ent;   

    outfile = fopen("Z:\\NH\\instructions.txt","wb"); 
    if (outfile == NULL) 
    { 
     return -1; 
    } 

    dir = opendir ("Z:\\NH\\sqltesting\\"); 
    if (dir == NULL) 
    { 
     fclose (outfile); 
     return -1; 
    } 

    while ((ent = readdir (dir)) != NULL) 
    { 
     fprintf (outfile, "%s\n", ent->d_name); 
    } 

    fclose (outfile); 
    closedir (dir); 
    return 0; 
} 
相关问题