修改C中二进制文件中的一些字节

时间:2015-12-26 17:38:35

标签: c file byte

有没有办法改变二进制文件中单个字节的值?我知道如果您以r+b模式打开文件,光标将位于现有文件的开头,您在该文件中编写的任何内容都将覆盖现有内容。

但我想在一个文件中只改变1个字节。我想你可以复制不应修改的文件内容,并在正确的位置插入所需的值,但我想知道是否还有其他方法。

我想要实现的一个例子: 将第3个字节更改为67

初始档案:

00 2F 71 73 76 95

写完后的文件内容:

00 2F 67 73 76 95

2 个答案:

答案 0 :(得分:5)

使用fseek移动到文件中的位置:

FILE *f = fopen( "file.name", "r+b" );
fseek( f, 3, SEEK_SET ); // move to offest 3 from begin of file
unsigned char newByte = 0x67;
fwrite( &newByte, sizeof( newByte ), 1, f );
fclose( f );

答案 1 :(得分:4)

使用fseek()定位文件指针,然后写出1个字节:

// fseek example
#include <stdio.h>

int main ()
{
    FILE * pFile;
    pFile = fopen("example.txt", "wb");
    fputs("This is an apple.", pFile);
    fseek(pFile, 9, SEEK_SET);
    fputs(" sam", pFile);
    fclose(pFile);
    return 0;
}

请参阅http://www.cplusplus.com/reference/cstdio/fseek/

对于现有文件,仅更改1个字符:

FILE * pFile;
char c = 'a';

pFile = fopen("example.txt", "r+b");

if (pFile != NULL) {
    fseek(pFile, 2, SEEK_SET);
    fputc(c, pFile);
    fclose(pFile);
}