C语言 C 以二进制模式读取/写入文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18293482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C reading/writing to a file in binary mode
提问by SevenOfNine
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:
我创建了一个包含 4000 个块的文件,块大小为 4096 字节。现在我想操作单个块并在不改变文件大小的情况下再次读取它们。实际上,我想将另一个文件中的块写入我创建的文件中的特定块。因此,我以二进制模式打开文件,如下所示:
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!
先感谢您!
回答by Carl Norum
From the fopenman page:
从fopen手册页:
``w'' Truncate to zero length or create text file for writing. The stream is positioned at the beginning of the file.
``w'' 截断为零长度或创建用于写入的文本文件。流位于文件的开头。
You're erasing the destination file every time you open it. You might be interested in aor a+:
每次打开目标文件时都会删除它。您可能对a或感兴趣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.
``a'' 开放写作。如果文件不存在,则创建该文件。流位于文件的末尾。对文件的后续写入将始终以当前的文件结尾结束,而不管是否有任何介入 fseek(3) 或类似内容。
``a+'' 可读写。如果文件不存在,则创建该文件。流位于文件的末尾。对文件的后续写入将始终以当前的文件结尾结束,而不管是否有任何介入 fseek(3) 或类似内容。
回答by David Elliman
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;
问题是您的搜索需要从文件开头到某个字节偏移量。由于块的长度为 4096,因此偏移量为 (long)i * 4096;
I think you are seeking to the wrong position as the freeBlocks[i] is presumably an address.
我认为您正在寻找错误的位置,因为 freeBlocks[i] 大概是一个地址。

