[Coco] Reading Files In DECB

William Astle lost at l-w.ca
Tue Aug 7 13:04:54 EDT 2018


Back in the day, I did arbitrary I/O on files by opening them in 
"direct" mode with a record size of 1 (specified as the fourth parameter 
of OPEN). That allows you to read and write any arbitrary byte in the 
file. It's fairly slow, though.

You could theoretically use the same idea with a larger record size. In 
your example, a record size of 80 would do since 800 is an exact 
multiple of 80.

I think something like this would theoretically work. Warning: Mailer 
Code™. YMMV. Line numbers omitted.

OPEN "D", #1, "FILE.EXT", 80
FIELD #1, 80 AS R$
GET #1,10
TX$ = R$

You could use TX$ as the FIELD variable, but if you're going to mess 
with it, or read other records, that would mess up the FIELD settings.

Note that the record number is just the byte offset divided by the 
record size. You'll want to use LOF() to make sure the file is actually 
large enough to contain the bytes you're looking for or you'll trigger 
an error when reading.

Of course, you need to choose your record size and offsets to line up. 
If, instead, you needed 80 bytes from offset 300, the above wouldn't 
work. Instead, you'd need the greatest common divisor of 80 and 300 
which is 20. Then you could do something like:

OPEN "D", #1, "FILE.EXT", 20
FIELD #1, 20 AS R$
GET #1, 15
TX$ = R$
GET #1, 16
TX$ = TX$ + R$
GET #1, 17
TX$ = TX$ + R$
GET #1, 18
TX$ = TX$ + R$

You can probably work out how you can write to arbitrary positions in 
arbitrary files the same way.

This degenerates to a record size of 1 in the worst case, in which case 
your record numbers would simply be the byte offset in the file.

This method will allow you to read arbitrary binary data from the file 
which is something that doesn't work well with sequential files.

For a related trick, you can get the byte length of any arbitrary file 
by opening it in direct mode with a record size of 1 and then requesting 
"LOF()" on it.

On 2018-08-07 08:18 AM, coco at jechar.ca wrote:
> 
>   Anyone
> 
>   I wonder if anybody has some basic program that can read the contents 
> of a portion of
>   an arbitrary file into a string.
> 
>   For Example suppose you wanted to read 80 characters from file X 
> starting at character 800
>   of the file which may be may be either binary or ascii into a string 
> say TX$.
> 
>   How would you do It my atempts are geting hung up on the FIELD command.
> 
>   Charlie
> 



More information about the Coco mailing list