Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change one character in a file without writing the whole file again?

How do I change one character in a file? Any nix-compliant programming language solution is welcome.

I wrote .pgm file and put the magic number to 'P2'. The correct one is 'P5'. Now I have 100000+ files to fix. Alternatively: how do I read my new file with pylab.imread()?

FYI: pgm is an ascii image file format http://netpbm.sourceforge.net/doc/pgm.html. pylab and PIL require magic number to be P5

br, Juha

edit: Thank you for all solutions. dd-method is the only that works. For curiosity, why the c and python do not?

like image 503
Juha Avatar asked Nov 29 '25 17:11

Juha


2 Answers

Talking about solutions not involving Python, one would be something like:

echo -n "P5" | dd of=yourfile.pgm conv=notrunc

That will cause dd to write "P5" at the beginning of the file, without truncating it

like image 163
redShadow Avatar answered Dec 02 '25 10:12

redShadow


In C:

FILE* f = fopen("file.txt", "r+b");
fputs("P5", f);
fclose(f);

It'll be the same procedure (open-as-binary/write/close) in just about any language.

Most importantly: First, backup everything.

EDIT: I removed the fseek because the magic string is at the beginning of the file, which is where fopen(..., "r+b") positions the file pointer.

like image 42
Marcelo Cantos Avatar answered Dec 02 '25 09:12

Marcelo Cantos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!