我正在尝试使用fgets读取“Danfilez.txt”的内容。但是在完成时程序返回一个随机值,我不确定为什么。我是编程新手所以非常感谢任何帮助!
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;
}
答案 0 :(得分:2)
由于您要从您想要使用的文件中读取和写入" w +"打开文件而不仅仅是" w"。
但是这不会解决问题,因为一旦你写完了那个文字,你在文件中的位置仍然在最后,所以你还需要重新调整位置才能使用fseek()
fseek(Danfile,0,SEEK_SET);
答案 1 :(得分: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.
尝试使用“r +”或“w +”。在写完一些文字后,您在文件中的位置将随文本一起向前移动。使用快退(文件*文件名)将您的位置直接移动到文件的开头。有关文件处理的更多信息,我建议检查 stdio 库中的内容: https://www.tutorialspoint.com/c_standard_library/stdio_h.htm