Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify some bytes in a binary file in C

Tags:

c

file

byte

Is there any way to change the value of a single byte in a binary file? I know that if you open the file in r+b mode, the cursor is positioned at the beginning of the existing file and anything you write in that file will overwrite the existing content.

But I want to change only 1 byte, for instance, in a file. I guess you could copy the content of the file that should not be modified and insert the desired value at the right place, but I wonder if there is any other way.

An example of what I would like to achieve: Change 3rd byte to 67

Initial file:

00 2F 71 73 76 95

File content after write:

00 2F 67 73 76 95
like image 776
Polb Avatar asked Dec 26 '15 17:12

Polb


2 Answers

Use fseek() to position the file-pointer and then write out 1 byte:

// 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;
}

See http://www.cplusplus.com/reference/cstdio/fseek/

For an existing file and only changing 1 char:

FILE * pFile;
char c = 'a';

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

if (pFile != NULL) {
    fseek(pFile, 2, SEEK_SET);
    fputc(c, pFile);
    fclose(pFile);
}
like image 174
Danny_ds Avatar answered Nov 10 '22 16:11

Danny_ds


Use fseek to move to a position in a file:

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 );
like image 28
Rabbid76 Avatar answered Nov 10 '22 16:11

Rabbid76