2016-11-28 12 views
2

FILE*オブジェクト(サイズは8 * 1024)の大きなバッファを設定しています.4バイトの書き込みをしてから4を読み込みますが、読み込みに失敗します。 FILE*をフラッシュすると、読み込みに成功します。fwrite()が0バイトを取得した後

typedef struct _MyFile {     /* file descriptor */ 
    unsigned char fileBuf[8*1024]; 
    FILE *file; 
} MyFile; 

int main() { 
    MyFile myFile; 
    int res; 
    char bufWrite[4] = { 1, 2, 3, 4 }; 
    char bufRead[4]; 

    /* Open file for both reading and writing */ 
    myFile.file = fopen("myfile.txt", "w"); 

    /* Change the file internal buffer size */ 
    setvbuf(myFile.file, myFile.fileBuf, _IOFBF, sizeof(myFile.fileBuf)); 

    /* Write data to the file */ 
    res = (int)fwrite(buf, 1, 4, myFile.file); 
    printf("write: res = %d\n", res); 

    /* Seek to the beginning of the file */ 
    fseek(fp, SEEK_SET, 0); 

    /* Read and display data */ 
    res = (int)fread(buf, 1, 4, myFile.file); 
    printf("read: res = %d\n", res); 
    fclose(myFile.file); 

    return 0;   
} 

出力は次のようになります。

write: res = 4 
read: res = 0 

私は8K以上のものを書いたりもwrite()の代わりfwrite()fread()作品を使用している場合。

事は使用できませんfflush() !!!

これを修正する方法はありますか?

+1

あなたはファイルを読み取り/書き込みで開こうとしましたか? 'fopen(" myfile.txt "、" rw ");' –

+0

バッファリングされていない呼び出し( 'open'、' read'、 'write')を使うことはできませんか? –

+0

@Eliand fopen( "myfile.txt"、 "w +"); –

答えて

2

書き込み専用モードでファイルを開いています。ハンドルは、あなたがそれを読みたいと認識していません。

だけで読み書きモードでファイルを開きます。

myFile.file = fopen("myfile.txt" , "w+"); 

私はそれをテストしているし、それが成功した読み取りバッファ内のデータを読み出します。

のみ書き込みモード:

write : res = 4 
read: res = 0 
bufRead: -83 20 82 117 

読み取り/書き込みモード:

write : res = 4 
read: res = 4 
bufRead: 1 2 3 4 

編集:私の最初の試みの使用奇妙な書き込み、戻り値の結果を働いたが与えた"rw"モード:

write : res = 0 
read: res = 4 
bufRead: 1 2 3 4 
関連する問題