2016-08-03 38 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; 
} 
相關問題