C fseek()返回0(成功),但读取的数据错误
使用C fseek()返回0(成功),但读取的数据错误,c,linux,file,C,Linux,File,使用fread和fwrite使用fopen和fseek读取正确数据时遇到困难。 情景: 1.将4K数据写入偏移量20。 2.从偏移量20读取4K数据。 3.将4K数据写入偏移量4K+10。 4.从偏移量4K+10读取4K数据。 我将流(文件*)缓冲区初始化为256K-因此数据保留在缓冲区中,实际上不会写入物理文件 typedef struct _MyFile { /* file descriptor */ unsigned char fileBuf[256
fread
和fwrite
使用fopen
和fseek
读取正确数据时遇到困难。
情景:
1.将4K数据写入偏移量20。
2.从偏移量20读取4K数据。
3.将4K数据写入偏移量4K+10。
4.从偏移量4K+10读取4K数据。
我将流(文件*
)缓冲区初始化为256K-因此数据保留在缓冲区中,实际上不会写入物理文件
typedef struct _MyFile { /* file descriptor */
unsigned char fileBuf[256*1024];
FILE *file;
} MyFile;
int main() {
MyFile myFile;
int res;
int bufWrite[8*1024] = { 0 };
int bufRead[8*1024];
/* Open file for both reading and writing and reading */
myFile.file = fopen("myfile.txt", "w+");
/* Change the file internal buffer size */
setvbuf(myFile.file, myFile.fileBuf, _IOFBF, sizeof(myFile.fileBuf));
/* Seek to offset 20 of the file */
res = fseek(myFile.file, 20, SEEK_SET);
if (0 != res)
{
printf("1st fseek fails\n");
goto Exit;
}
bufWrite[0] = 1;
/* Write data to the file(buffer) */
res = (int)fwrite(bufWrite, 1, 4*1024, myFile.file);
if (4+1024 != res)
{
printf("1st write fails\n");
goto Exit;
}
/* Seek to offset 20 of the file */
res = fseek(myFile.file, 20, SEEK_SET);
if (0 != res)
{
printf("2nd fseek fails\n");
goto Exit;
}
/* Read and display data */
res = (int)fread(bufRead, 1, 4*1024, myFile.file);
if (4+1024 != res)
{
printf("1st read fails\n");
goto Exit;
}
/* Seek to offset 4K + 10 of the file */
res = fseek(myFile.file, 4*1024+10, SEEK_SET);
if (0 != res)
{
printf("3rd fseek fails\n");
goto Exit;
}
bufWrite[0] = 2;
/* Write data to the file(buffer) */
res = (int)fwrite(bufWrite, 1, 4*1024, myFile.file);
if (4+1024 != res)
{
printf("2nd write fails\n");
goto Exit;
}
/* Seek to offset 4K + 10 of the file */
res = fseek(myFile.file,4*1024+10, SEEK_SET);
if (0 != res)
{
printf("4th fseek fails\n");
goto Exit;
}
/* Read and display data */
res = (int)fread(bufRead, 1, 4*1024, myFile.file);
if (4+1024 != res)
{
printf("2nd read fails\n");
goto Exit;
}
fclose(myFile.file);
Exit:
return 0;
}
第一个fread
有正确的数据,但第二个fread
没有,
第二个fread
的数据是10个零,然后才是数字2。
我做错了什么?
fseek()
不知道如何使用缓冲流吗?假设所有调用都没有失败,代码看起来不错(除了所用函数缺少的原型)。我无法重现您描述的行为。这应该适用于GCC支持的任何C方言。好的,那么您使用的是哪个GCC,哪个操作系统?(gcc-version;uname-a
)到另一个编辑器。。。不要编辑其他人的代码,如果它有错误,那么它们可能是问题的一部分。如果没有调用失败,代码看起来不错(除了所用函数缺少原型)。我无法重现您描述的行为。这应该适用于GCC支持的任何C方言。好的,那么哪个GCC,你正在使用哪个操作系统?(gcc-version;uname-a
)到另一个编辑器。。。不要编辑其他人的代码,如果它有错误,那么它们可能是问题的一部分