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()を使用している間、open のオプションを引数として関数に渡します。リストは次のとおりです。

"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 に答える