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;
}
Im reading a specified chunk of a file with fseek and fread functions and then writing it to another file. For some reason in the destination file I get about 20 bytes overlap between every chunk written in it.
Could anyone, please, help me identifying the source of this garbage? It is definitely caused by the fseek function, but I cant figure out why.
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我猜您使用的是 Windows,并且正在遭受 Windows 文本模式的弊端。将
"b"
添加到传递给fopen
的标志中,即I'm guessing you're on Windows and suffering from the evils of Windows' text mode. Add
"b"
to the flags you pass tofopen
, i.e.看起来您正在从
Dest
文件读取并写入源文件
可能,您必须将
Dest
更改为Src
。It seems you are reading from
Dest
fileand writing to source
Probably, you have to change
Dest
toSrc
.