2016-08-03 7 views
-4

누구나 전에이 일을했다면 궁금했습니다.C에서 struct에서 문자열을 가져 오는 방법은 무엇입니까?

구조체에서 문자열을 가져 오는 데 문제가 있습니다. 내가 뭘하려고 해요 특정 구조체에서 문자열을 가져 와서, 그 문자열을 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 포인터가 다음 위의 문이

로 변경 것이었다 fprintf의 사람 페이지에서
1

는 함수 선언은 다음과 같습니다 당신은 첫 번째 인수를 포함하지 않았다

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; 
} 
관련 문제