2016-08-03 10 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に渡すことができる方法はありますか?

char dname[some_number]; 

と構造物

ent //is not a pointer 

行うと仮定すると

+3

heh?マニュアルページを読んだことがありますか? –

+0

また、構造体に関する情報もありません。 – sjsam

+3

['fprintf()'](http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html)は、最初の引数として書式文字列を取りません。 – dhke

答えて

0

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

entポインタは、その後、上記の文は

に変更しますされて
1

fprintfのmanページから、関数の宣言は次のとおりです。

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; 
} 
関連する問題