read/write arbitrary chunk of a file

Started by Sammo, December 18, 2003, 06:01:18 AM

Previous topic - Next topic

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

#1
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:



(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

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