簡體   English   中英

如何使用fgets從文件讀取?

[英]How to read from a file using fgets?

我正在嘗試使用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;
}

由於您正在從文件中讀取和寫入文件,因此您想使用“ w +”打開文件,而不僅僅是“ w”。

但這不能解決問題,因為一旦您寫完該文本,文件中的位置仍然在末尾,因此您還需要重置位置,然后才能使用fseek()讀取任何內容。

fseek(Danfile,0,SEEK_SET);

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM