2017-03-08 4 views
0

fgets를 사용하여 "Danfilez.txt"의 내용을 읽으려고합니다. 그러나 완료시 프로그램은 임의의 값을 반환하며 이유는 확실하지 않습니다. 나는 프로그래밍에 익숙하지 않아 어떤 도움을 주시면 감사하겠습니다!fgets를 사용하여 파일을 읽는 방법?

int main() 
{ 
    FILE* Danfile = fopen ("Danfilez.txt", "w"); 
    char fileinfo [50];// Character arrays for file data // 

    if (Danfile == NULL) 
    { 
     printf ("ERROR\n"); 

    } 

    else 
    { 
     printf("Everything works!\n"); 
     fprintf (Danfile, "Welcome to Dan's file."); 
     fgets(fileinfo,50,Danfile); 
     printf("%s\n",fileinfo); 
     fclose (Danfile); // CLOSES FILE // 
    } 


    return 0; 
} 

답변

2

"w +"를 사용하여 "w"가 아닌 파일을 열려면 파일에서 읽고 쓰고 있어야합니다.

하지만 텍스트를 작성한 후에도 파일의 위치가 끝났기 때문에 아무 것도 읽을 수 없으므로 위치를 재설정해야합니다. fseek()

fseek(Danfile,0,SEEK_SET); 
+0

헥타르 아 : 자세한 내용은 내가 표준 입출력 내부 라이브러리 무엇인지 확인하는 것이 좋습니다 처리 파일 관련! 고마워, 나는 재미 있기 전에 fseek를 건너 가지 않았다. 그래서 나는 당신이 읽기 전에 파일의 시작에 있는지 확인합니다. 건배 –

+0

예에서 네, 파일 내의 위치를 ​​0으로 "설정"합니다. 또한 파일의 현재 위치 나 끝과 관련하여 위치를 지정할 때도 사용할 수 있습니다. –

0

사용하는 동안 는 fopen() 당신은 연료 소모량에 대한 인수로 개방에 대한 옵션을 전달합니다. 여기 목록입니다 :

"r" - Opens the file for reading. The file must exist. 
"w" - Creates an empty file for writing. If a file with the same name already exists, 
     its content is erased and the file is considered as a new empty file. 
"a" - Appends to a file. Writing operations, append data at the end of the 
     file. The file is created if it does not exist. 
"r+" - Opens a file to update both reading and writing. The file must exist. 
"w+" - Creates an empty file for both reading and writing. 
"a+" - Opens a file for reading and appending. 

는 또는 "w +""+ R"을 사용해보십시오. 텍스트를 작성한 후 파일의 위치가 텍스트와 함께 앞으로 이동합니다. rewind (FILE * filename)을 사용하여 위치를 파일의 시작 부분으로 바로 이동하십시오. https://www.tutorialspoint.com/c_standard_library/stdio_h.htm

관련 문제