fseek()导致数据重叠

时间:2011-06-11 21:48:36

标签: c fseek

我正在使用fseek和fread函数读取文件的指定块,然后将其写入另一个文件。由于某种原因,在目标文件中,我在其中写入的每个块之间重叠大约20个字节。

有人可以帮我确定一下这个垃圾的来源吗?它肯定是由fseek函数引起的,但我无法弄清楚为什么。

FILE *pSrcFile; 
FILE *pDstFile; 

int main()
{
int buff[512], i;
long bytesRead;

pSrcFile = fopen ( "test.txt" , "r" );
pDstFile = fopen ( "result1.txt", "a+");

for(i = 0; i < 5; i++)
{
    bytesRead = _readFile ( &i, buff, 512);
    _writeFile( &i, buff, bytesRead);
}

fclose (pSrcFile);
fclose (pDstFile);
}

int _readFile (void* chunkNumber, void* Dstc, long len) 
{
int bytesRead;
long offset = (512) * (*(int*)chunkNumber);

fseek( pSrcFile, offset, SEEK_SET);

bytesRead = fread (Dstc , 1, len, pSrcFile);

return bytesRead;
}

int _writeFile (void* chunkNumber, void const * Src, long len) 
{
int bytesWritten;
long offset = (512) * (*(int*)chunkNumber);

bytesWritten = fwrite( Src , 1 , len , pDstFile );

return bytesWritten;
}

2 个答案:

答案 0 :(得分:2)

我猜你在Windows上遭受了Windows的祸害。文字模式。将"b"添加到您传递给fopen的标记,即

pSrcFile = fopen ( "test.txt" , "rb" );
pDstFile = fopen ( "result1.txt", "a+b");

答案 1 :(得分:0)

您似乎正在阅读Dest文件

bytesRead = fread (Dstc , 1, len, pSrcFile);

并写信给

bytesWritten = fwrite( Src , 1 , len , pDstFile );

您可能需要将Dest更改为Src

相关问题