Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing one byte in a file in C

Tags:

c

I have a file stream open and ready.

How do I access and change a single Byte in the stream such that the change is reflected on the file?

Any suggestions?

like image 872
Yuval Adam Avatar asked May 10 '09 11:05

Yuval Adam


2 Answers

#include "stdio.h"

int main(void)
{
    FILE* f = fopen("so-data.dat", "r+b"); // Error checking omitted
    fseek(f, 5, SEEK_SET);
    fwrite("x", 1, 1, f);
    fclose(f);
}
like image 185
RichieHindle Avatar answered Sep 22 '22 22:09

RichieHindle


FILE* fileHandle = fopen("filename", "r+b"); // r+ if you need char mode
fseek(fileHandle, position_of_byte, SEEK_SET);
fwrite("R" /* the value to replace with */, 1, 1, fileHandle);
like image 42
mmx Avatar answered Sep 25 '22 22:09

mmx