Search code examples
cfopenfwritefread

C reading a File in binarymode and write to an output file


I created a File of 4000 blocks with a blocksize of 4096 Bytes. I wrote to some specific blocks in this file and now I want to read these blocks and write the result into a new output file.

Therefore I open the file I created in "rb" mode (storeFile) and the outputfile in "wb" mode (outputFile) as follows:

FILE * outputFile=fopen(outputFilename,"wb");
FILE * storeFile=fopen(storeFilename, "rb");

now I am trying to seek for the right position and read all blocks to the new file (outputfile):

for(i=0; i<BlocksUsed; i++)
{
    fseek(storeFile,blocksToRead[i]*4096,SEEK_SET);
    fread(ptr, 4096,1,storeFile);
    fwrite(ptr,4096,1outputFile);
    ...
    rewind(storeFile)
 }

unfortunately this code leads to a file which is not the file I wrote to the storeFile. The files' size is BlockUsed*4096Bytes.

What am I doing wrong?

Thank you in advance!


Solution

  •  fseek(storeFile,blocksToRead[i]*4096,SEEK_SET);
     int n = fread(ptr, 4096,1,storeFile);
     if (n <0)
     {printf("read error\n");return -1;}
     if(fwrite(ptr,n,1outputFile) != n)
     {printf("write error\n"); return -1;}
        ...
     //rewind(storeFile)// no need . since you use fseek