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

How to change one character in a file? Any solution compatible with nix-compatible software is welcome.

I wrote a .pgm file and put the magic number in 'P2'. The correct one is "P5". Now I have 100,000+ files to fix. Alternatively: how can I read my new file using pylab.imread ()?

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

br, juha

edit: Thanks for all the solutions. Only the dd method works. For curiosity, why is c and python not?

+3
source share
5 answers

Speaking of non-Python solutions, one would need something like:

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

This will force dd to write “P5” at the beginning of the file without truncating it.

+4
source

In python, you can write a memory card using the mmap module .

f = open("yourfile.pgm", "rb+")
map = mmap.mmap(f.fileno(), 0)
map[1] = "5"
map.close()
+1
source

C:

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

(open-as-binary/write/close) .

: .

EDIT: fseek, , fopen(..., "r+b") .

+1

, , x , , .

0

, , , , , .

0

Source: https://habr.com/ru/post/1776659/


All Articles