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()
!!!
これを修正する方法はありますか?
あなたはファイルを読み取り/書き込みで開こうとしましたか? 'fopen(" myfile.txt "、" rw ");' –
バッファリングされていない呼び出し( 'open'、' read'、 'write')を使うことはできませんか? –
@Eliand fopen( "myfile.txt"、 "w +"); –