Write to portions of file
Is it possible to write data to a specific portion of a file without re-writing the entire file? Let me elaborate:
Let's say I have a 2.7 Mb document. If I want to modify 32 bytes of data in the middle of the file, I would normally read the entire 2.7 Mb into memory, modify the data, then re-write the entire 2.7 Mb back to the file.
What I would like to do is:
1. Read only the 32 bytes of interest into memory
2. Modify it.
3. Replace the old 32 bytes with the new.
Can this be done?
Open the file for random access like this:
recLen=1 OPEN "R",#1,filename$,recLen,volRefNumRead your 32 bytes out of the file like this:
posInFile=3200 'position in file you want to start reading RECORD #1, posInFile READ FILE #1, @myString$+1, 32To write back to the file reset the record pointer and write the data like this:
posInFile=3200 'position in file you want to start writing RECORD #1, posInFile WRITE FILE #1, @myString$+1, 32
Yes indeed. Here's what you do:
1. Open the file in "R" mode. That will let you read from and write to the file. Also, pay attention to how you set the "reclen" parameter. The simplest thing to do is to set it to "1" (do _not_ leave it blank, or Step 2 won't work right). Your OPEN statement should look something like this:
OPEN "R", #fileID, fileName$, 1, vRefNum%2. Use the RECORD statement to position the "file mark" to the correct place in the file. The "file mark" is an internal pointer which indicates where in the file the next i/o operation will begin. Assuming you have set your file's record length to 1 in Step 1, you would do this:
RECORD #fileID, byteOffset&where byteOffset& is the number of the first byte you want to read. In the typically perverse world of programming, the first byte in the file is numbered zero. So if you wanted to start reading at the 10,000th byte in the file, you'd set byteOffset& to 9999.
3. Now just input from the file, using your favorite file input command (like INPUT#, READ#, READ FILE, etc.)
4. The file mark automatically advances after you do the input in Step 3, so it's no longer at the same offset it was at before. Therefore, when you get ready to write the data back to the file, you have to set the file mark position again:
RECORD #fileID, byteOffset& '(same byteOffset& value as before)5. Now just write to the file, using your favorite file output command (like PRINT#, WRITE#, WRITE FILE, etc.)
And that's about all there is to it. If you want to get fancy, you can use other numbers besides "1" as your recLen, but then you have to calculate the RECORD parameter differently. Just stick with "1" for now.