C以二进制模式读取/写入文件 [英] C reading/writing to a file in binary mode

查看:282
本文介绍了C以二进制模式读取/写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个4000个块的文件,块大小为4096字节. 现在,我想操作单个块并在不更改文件大小的情况下再次读取它们. 实际上,我想将另一个文件中的块写到我创建的文件中的特定块中. 因此,我将以二进制模式打开文件,如下所示:

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.

我在做什么错了?

提前谢谢!

推荐答案

fopen手册页中:

``w''截短为零长度或创建要写入的文本文件.流位于文件的开头.

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

每次打开目标文件时都将其擦除.您可能对aa+感兴趣:

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

``a''开放供写作.如果文件不存在,则创建该文件.流位于文件的末尾.无论随后的fseek(3)或类似内容如何,​​后续对该文件的写入将始终在该文件的当前末尾结束.

``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 +''打开供阅读和写作.如果文件不存在,则创建该文件.流位于文件的末尾.无论随后的fseek(3)或类似内容如何,​​后续对该文件的写入将始终在该文件的当前末尾结束.

``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.

这篇关于C以二进制模式读取/写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆