2017-03-08 186 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