read/write arbitrary chunk of a file

Q&A's, tips, howto's
Post Reply
Sammo
Posts: 180
Joined: Sat Dec 06, 2003 6:11 pm
Location: Loveland, Colorado USA

read/write arbitrary chunk of a file

Post by Sammo »

With (slice (read-file "filename") start count) I can read any contiguous chunk of bytes from a file, but from a very large file how might I read and then later write a contiguous block of, say, 128 bytes? In particular, for reading and later updating v1.0 and v1.1 mp3 tags I'd like to read and write the last 128 bytes in a largish file. I thought that (seek an-open-file -128) and then a (read-buffer ...) would be a good start, but that didn't work. Is (slice (read-file ...)) the way to go or have I missed the obvious?

Lutz
Posts: 5279
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

For 'seek' -128 doesn't work, only -1 for the end of file. But it may be a good idea to implement negative offsets for 'seek' in a future version.

For now you can specify only positive offsets. Do the following:

Code: Select all

(set 'size (first (file-info "myfile.mp3")))
(set 'file (open "myfile.mp3" "u"))
(seek file (- size 128))
(read-buffer file 'buff 128)

; .. change buff ..

(seek file (- size 128))
(write-buffer file buff 128)
(close file)
Lutz

Sammo
Posts: 180
Joined: Sat Dec 06, 2003 6:11 pm
Location: Loveland, Colorado USA

Post by Sammo »

Fabulous! Thank you very much. With this straightforward code, I don't see a strong need to improve (seek ...) to accept negative offsets.

Post Reply