Changing one byte in a file in C

I have a file stream open and ready.

How do I access and change one byte in a stream so that the changes are reflected in the file?

Any suggestions?

+6
c
source share
3 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); } 
+8
source share
 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); 
+5
source share
 #include <stdio.h> /* standard header, use the angle brackets */ int main(void) { char somechar = 'x'; /* one-byte data */ FILE* fp = fopen("so-data.txt", "r+"); if (fp) { fseek(fp, 5, SEEK_SET); fwrite(&somechar, 1, 1, fp); fclose(fp); } return 0; /* if you are on non-C99 systems */ } 
+3
source share

All Articles