【问题标题】:How to read from a file using fgets?如何使用 fgets 从文件中读取?
【发布时间】:2017-03-08 11:55:36
【问题描述】:

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

【问题讨论】:

    标签: c fgets scanf file-pointer


    【解决方案1】:

    由于您既要读取文件又要写入文件,因此您想使用“w+”来打开文件,而不仅仅是“w”。

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

    fseek(Danfile,0,SEEK_SET);
    

    【讨论】:

    • 啊哈!谢谢,在这很有趣之前我还没有遇到过 fseek 。所以我想它只是确保你在阅读之前处于文件的开头?干杯
    • 在那个例子中,是的,它在文件中将位置“设置”为 0。您也可以使用它来定位自己相对于当前位置或文件末尾的位置。
    【解决方案2】:

    使用 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

    【讨论】:

      猜你喜欢
      • 2019-05-29
      • 2015-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-23
      • 1970-01-01
      相关资源
      最近更新 更多