C reading/writing to a file in binary mode

自闭症网瘾萝莉.ら 提交于 2019-12-06 15:37:45

问题


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!


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/18293482/c-reading-writing-to-a-file-in-binary-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!