7.2 File Commands and Functions Description Visual Basic has three types of files that may be opened and accessed in a program: a) Sequential access to files reads and writes data line by line as if it is printed output. Another way to think of data in a sequential file is songs on a cassette tape, one after the other. b) Random access files are like databases. A record within one of these files is a complete set of data for a single entry. This type of access is convenient when the file contains homogeneous type data, such as several peoples' names, addresses, phone numbers and ages. c) Binary access to files reads and writes data byte by byte to any location within the file. In a binary file, information is recorded in its most primitive form: the byte. To OPEN a file Before you read from or write to any of the above types of files, you must open it. You accomplish this by using the Open statement: Open "Sample.txt" For Output As #1 - After the Open command is the name of the file you want to open (Sample.txt) - The filename must be a string variable or enclosed in quotation marks, and unless it is in the current directory, you need to provide its path. - After the filename and the keyword For, the mode of file access is stated. This indicates what purpose the file is being opened for, one of three options for sequential type files: Input - reads data from a file (file has to already exist) Output - write data to a new file (creates new file if it doesn't exist, **replaces** one if it already exists) Append - adds information to a sequential file (file should already exist) - The As # section of the statement assigns a file number to the file so that other statements may refer to the file by its number rather than its pathname. To CLOSE a file As soon as a program is finished working with a file it should be closed. This can be accomplished simply with the Close command, followed by the file identifier. For example, to close the above file, give the command: Close #1 The Close command without a file identifier closes all open files. To WRITE to a file The Write # command provides one way to send information to a sequential file opened for Output or Append. It is probably the preferred way since it automatically inserts commas between output items and quotation marks around strings as they are written to file (makes read back from file easier). Here is an example of a fragment of code that sends information to a file named SAMPLE.TXT: Open "SAMPLE.TXT" For Output As #4 Write #4, "Testing", 1, 2, 3 Close #4 As shown, more than one output item can be written to a file at a time, they simply need to be separated by commas for each. Data stored in variables can be written similarly by listing their name(s). To Read from a file(INPUT statement) To read information from a file, you must open the file for input using its name and give it a file identifier not in use by another file (it doesn't have to be the same identifier that it was set up with originally). The easiest way to find an identifier that hasn't been used already is with the FreeFile command. To do this, declare an integer variable (e.g. FileNum) and use the statement: FileNum = FreeFile before an Open statement: Open "SAMPLE" For Input As #FileNum Once the file is open, there are a few ways to retrieve the data stored in it. The Input # looks and works similar (but opposite!) to the Write # statement: Dim Var1 as String Dim Var2 as Integer Input #FileNum, Var1, Var2 would read in the first two (comma-delimited) pieces of info into the two variables Var1 and Var2. There is also an Input function (ie. It returns a result): Dim ShortWord as String ShortWord = Input (4, #FileNum) The above would retrieve the first four characters from the file (characters, spaces, commas, whatever!) and store them in the variable ShortWord. The END OF FILE (EOF) Statement When inputting information from a file, you are not always going to know how much information there is to be read in from a particular file. To handle this properly you might use something that looks like the following pseudocode: While there is data remaining in the file Get the next chunk of data Process it Loop To accomplish this you'll need to know when you've reached the end of a file. In Visual Basic this is done using the EOF() statement, putting the file identifier in the brackets. Here is a small program that would read back all the information stored in a file (for data outputted with Write #) Dim FileNum As Integer ' to hold free identifier number Dim Holder As String ' to input data into FileNum = FreeFile ' get free identifier number Open "Sample.txt" For Input As FileNum Do Until EOF(FileNum) Input #FileNum, Holder ' This is where you would process Holder Loop Close #FileNum Activity 7.2.1: Using the above, give the statement(s) that would accomplish the following: 1. Open a file named "Readme.Now" with file identifier #3, so that data may be retrieved from it. 2. Input the first 10 characters from the above file into a string variable called Beginning. 3. Open a file named "Hiscores.txt" using the first free identifier number, and make it so that information can be added to data already in the file 4. Output your name, age and phone number to the file opened in question #3. 5. Close the above files. Activity 7.2.2 - Name Saver To further demonstrate the commands shown above, you are going to modify the program you created in Unit 2 (My Personal Information). The modifications are going to have you writing the information to a data file, and then retrieving it into a text box: 1) Retrieve the Personal Information program that you created in the second activity of Unit 2 (create it if you have it!) 2) Leave the Exit button as it is but remove the Display command button, and then add the following buttons: Name = cmdAddInfo Caption = "ADD THIS INFO TO FILE" Name = cmdReadNames Caption = "SEE NAMES FROM FILE" Name = cmdClear Caption = "CLEAR ALL TEXT BOXES" 3) Add another text box at the bottom of the form: Name = txtNamesFromFile MultiLine = True 4) Add a Line to separate the two sections so that your form resembles: 5) Add the coding for the command buttons you just added: Private Sub cmdAddInfo_Click() Dim FileNum As Integer ' variable for file identifier FileNum = FreeFile ' find identifier not in use ' open file for append so that we don't erase data that is already there! Open "NAMES.TXT" For Append As #FileNum ' the following should be typed on the same line in VB Write #FileNum, txtFirstName.Text, txtLastName.Text, Val(txtHeight.Text), txtHairColor.Text Close #FileNum ' close file, otherwise could cause problems! End Sub Private Sub cmdReadNames_Click() Dim FileNum As Integer ' Holds file identifier # Dim FileLength As Integer ' Holds length of file in bytes Dim Names As String ' Holds all info read from data file FileNum = FreeFile ' Assigns free file identifier Open "NAMES.TXT" For Input As #FileNum ' Opens up names file FileLength = LOF(FileNum) ' Puts length of the file in bytes into FileLength Names = Input(FileLength, #FileNum) ' Inputs all data into Names txtNamesFromFile.Text = Names ' Puts all data read into text box Close #FileNum End Sub Private Sub cmdClear_Click() txtFirstName.Text = "" 'Empty all the text boxes txtLastName.Text = "" txtHeight.Text = "" txtHairColor.Text = "" txtNamesFromFile.Text = "" End Sub 6) Run the program. Try entering and reading a few names. Notice how the data appears. 1. What does the Write # command do to string data (e.g. the first names)? 2. What does the Write # command do to numeric values (e.g. heights)?