When you open a file for RANDOM or BINARY access you may want to move inside the file back and forth before reading or writing data. There are many functions and statements that help you to move the file pointer. Before going into details, let's explain what the file pointer is.
A file is a series of bytes stored on the disk. Whenever you read a byte from a file you do it from a certain position. The file pointer of the opened file identifies this position. When you read a line or some bytes from a file the file pointer automatically moves after the last character of the line. Therefore the next read will go on reading the next available unread character of the file. The same is true for writing the file. Whenever you write bytes to a file the file pointer associated with the opened file will move after the last position written.
If the file pointer is positioned after the very last byte of the file reading will result an end-of-file signal and the function EOF(fn) will be TRUE. If we try to write to the file in the same situation the length of the file will increase,
To get the actual length of an opened file you have to call the function LOF(fn) that stands for Length Of File. To get the current position of the file pointer you have to call the function POS(fn). To position to a certain position of an opened file you have to write:
seek #fn, position
where position is the number of bytes, or records from the start of the file. When you want to position to the start of the file, you can therefore write either
seek #fn, 0
Rewind is nothing else than a short form for seek#fn,0 because it is often needed and is more readable.
The functions LOF and POS return values in terms of records. If there is no record length specified in the statement open you can treat the return values as counts of bytes. On the other hand if there is a record length larger than one specified on the statement open these functions return a value in terms of records. LOF tells you how many records there are in the file and POS tells you which record the file pointer is positioned in.
You have to be careful interpreting the returned values of these functions with files opened with record length more than one. LOF tells you how many records there are in the file actually, but there may be some more bytes after the last complete records. POS tells you which record the file pointer is positioned in, but it does not guarantee that the file pointer is positioned on the first byte of the record.
There is a function named FILELEN that gives the length of a file based on the name of the file. The argument for this function is the name of the file, while the argument of LOF is the file number of the opened file.
Another difference is that FILELEN returns the size of the file in terms of bytes always and never in terms of records. This behavior becomes obvious if you recall that record length is specified when a file is opened and FILELEN works on unopened files.