0

我正在尝试使用 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;
}
4

2 回答 2

2

由于您正在从文件中读取和写入,因此您希望使用“w+”来打开文件,而不仅仅是“w”。

但这并不能解决问题,因为一旦您写出该文本,您在文件中的位置仍位于末尾,因此您还需要重置位置,然后才能读取使用中的任何内容fseek()

fseek(Danfile,0,SEEK_SET);
于 2017-03-08T12:04:55.877 回答
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+"。写入一些文本后,您在文件中的位置将随着文本向前移动。使用rewind(FILE* filename)将您的位置直接移动到文件的开头。有关文件处理的更多信息,我建议检查stdio库中的内容: https ://www.tutorialspoint.com/c_standard_library/stdio_h.htm

于 2017-03-08T14:46:57.940 回答