Using Files: Section V
This section will discuss how to read data from random parts in a binaryfile, and will look at file locking.
Author: Jens G. BalchenBefore You StartYou should be familiar with binary file editing, as explained in Section IV.Moving From One Position To AnotherIn the previous 4 sections, we have read a file from start to end. There has been no way to move backwards in a file, and no way to move forwards without first reading everything up to that position.This is probably why Visual Basic has the Seek command. There are two ways to use Seek; as a function and as a command. If you use it as a function, it will return the current position within the file: Position = Seek(1) Similarly, if you want to move to a specific location in the file, you use it this way: Seek #1, Position The ability to move around in a file can be important when the position of a data block is variable. Some file formats define a data header, with pointers to the positions in the file where the data block is stored. Here's an example on how to read one byte from position 4 and one from position 42:
Dim Data As String * 1 In this example, the use of Seek is a waste of time. The Get command can take a position to read from as an argument, so when you only need to read one set of data from a given position, you might as well skip the Seek. But if you want to read several blocks of data (use the Get command several times), you might find the Seek command more convenient. The Seek command works just as well with Put as with Get. In fact, it works on files opened for Input or Append as well, but it's a whole lot harder to figure out where a line starts when you have to give the argument in bytes. Locking FilesSometimes you want to make sure no one else interferes with you when you're reading or writing a file. For this purpose, we have the Lock option. Specifying it on the Open command line, you can prevent others from either reading, writing or both.You use it like this:
Open "C:\Windows\My File.txt" For Input Lock Read Write As #1 You can skip the Read command or the Write command if you want to allow others to perform that action on the file. Usually, the file locking option is used when you have several applications accessing a file at the same time. Through error trapping, Visual Basic allows you to detect when a file has been locked. This will be discussed in the next section. Next sectionThe time has come to look at error trapping relating to files and directories. |
||
Editor: Jens G. Balchen Last update: 2024-12-21 Copyright 1995-2024 VBI |