C reading/writing to a file in binary mode

2019-04-17 07:34发布

I created a File of 4000 blocks with a blocksize of 4096 Bytes. Now I want to manipulate single blocks and read them again without changeing the files' size. Actually I want to write blocks out of another file to specific blocks in the file I created. Therefore I am opening the Files in binarymode like this:

FILE * storeFile=fopen(targetFile, "wb");  // this one I created before
FILE * sourceFILE=fopen(sourceFile,"rb");

now I am trying to read stuff to a pointer

char * ptr=malloc(4096);
...
for(i=0; i<blocks_needed; i++)
{
    fread(ptr,4096,1,sourceFile);
    // now I am going to the position of the blocks I want to write to
    fseek(storeFile,freeBlocks[i]*4096,SEEK_SET);
    // and now I am writing it to the File I created before
    fwrite(ptr,4096,1,storeFile);
...
}

For some reason the File I created before changes it's size and becomes a copy of the file I wanted to write into it.

What am I doing wrong?

Thank you in advance!

2条回答
一夜七次
2楼-- · 2019-04-17 08:05

The problem is that your seek needs to be to some byte offset from the start of the file. As the blocks are 4096 in length the offset would be (long)i * 4096;

I think you are seeking to the wrong position as the freeBlocks[i] is presumably an address.

查看更多
混吃等死
3楼-- · 2019-04-17 08:17

From the fopen man page:

``w'' Truncate to zero length or create text file for writing. The stream is positioned at the beginning of the file.

You're erasing the destination file every time you open it. You might be interested in a or a+:

``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.

``a+'' Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.

查看更多
登录 后发表回答