2017-03-08 185 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()函數傳遞開作爲參數傳遞給該funtion的選項。這裏是清單:

"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. 

嘗試使用「R +」「W +」。寫入一些文本後,文件中的位置將隨文本一起向前移動。使用快退(文件*文件名)將您的位置直接移動到文件的開頭。欲瞭解更多有關文件處理的信息,我建議檢查內部是什麼stdio庫: https://www.tutorialspoint.com/c_standard_library/stdio_h.htm