Search code examples
cfseek

fseek() causing an overlap in the data


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;
}

Solution

  • 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");