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 garb开发者_StackOverflow社区age? 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;
}
I'm guessing you're on Windows and suffering from the evils of Windows' text mode. Add "b"
to the flags you pass to fopen
, i.e.
pSrcFile = fopen ( "test.txt" , "rb" );
pDstFile = fopen ( "result1.txt", "a+b");
It seems you are reading from Dest
file
bytesRead = fread (Dstc , 1, len, pSrcFile);
and writing to source
bytesWritten = fwrite( Src , 1 , len , pDstFile );
Probably, you have to change Dest
to Src
.
精彩评论