File Handling As you've used your computer, you've no doubt noticed that most applications save and load data to and from your hard disk. The applications you write with Visual Basic don't have to be any different; they, too, can save information to a disk file. Steps in Accessing a File Simple file handling is actually an easy process, after you get the hang of it. However, you need to perform three steps to be sure that your program's data gets properly tucked away in that binary home called a file. Those steps are as follows: 1. Open the file 2. Send data to the file or read data from the file 3. Close the file Opening a File Probably the most complicated part of managing file 1/0 (input/output, remember?) is opening the file in the proper mode. You see, not only can files be used to save and load data, but they also can be used to save and load specific kinds of data in specific ways. For example, there's a big difference between opening a file to read a line of text and opening a file to read a database record, even though a file must be opened in both cases. Specifically, you can open a file in one of five different modes: Append Binary Input Output Random These mode thingies are not as confusing as they might seem to be. First, because you're just starting out, you can forget about the Binary and Random modes. The remaining modes are easy to understand. To prove that claim, you're about to open a file in output mode, which makes good sense. You can't, after all, load data from a file until you've saved data to the file. Here's the Visual Basic statement that opens a file in the output mode: Open 'c:\MyFile.dat" For Output As #1 The keyword open tells Visual Basic that you're about to open a file. The string that follows the open keyword is the path and name of the file you want to open. In this case, the file is called MyFile.dat and is located in the root directory of drive C. Now comes the part that determines the file mode. See the For output? That tells Visual Basic you want to open the file in the output mode. This mode enables a program to save data to the disk file. In this case, the file is MyFile.dat. If the file doesn't already exist, Visual Basic creates it. If the file does exist, Visual Basic gets the file ready to accept output from your program, which includes erasing the current contents of the file. That's all there is to opening a file, Except for that mysterious AS #1 tacked on the end of the line. Every time your program opens a file, the program needs a way to refer to the file. The same way your friends might refer to you, your Visual Basic program must refer to the open file with a number. In this case, that number is 1. Saving Data to the File Your file is now open, and waiting for you to put some data into the file, something you can do with a Visual Basic command like this: Print #1, "This is a test" As you undoubtedly realize, the keyword Print, which you've run into before in other contexts, tells Visual Basic you want to print data to a file. Visual Basic knows you're printing to a file rather than to the screen, thanks to the #1 after the Print keyword. The number is the same number the program used to open the file. Remember the As #1 part of the Open statement? Punctuation Is Important! When you are typing program lines, make sure you get all the punctuation right. Leaving out something as simple as a comma can bring your program to a crashing halt For example, don't forget the comma in the Print statement, between the file number and the data to save. After the file number, you place a comma and follow it with the data you want to save to the file. In this case, the data is the string "This is a test". After Visual Basic has performed this command, your file will contain the string. Closing the File After you place data into the file, you must close the file; otherwise, you might wind up losing data. To close a file, you call upon the ever trusty Close statement, like this: Close #1 You've probably already figured out that the number after the Close keyword is the same number the program gave the file when it opened it with the open statement. Entering the Buffer Zone Closing files in a Visual Basic program (and most programs written in other languages, as well) is important because not all the data you've sent to the file has necessarily arrived there before you close the file. The reason for this anomaly is something called buffering. Because disk drives are so slow compared with computer memory, Visual Basic doesn't actually send data directly to the disk file. Instead, it saves up the data in your computer's memory until it has enough data to be worth taking the time to access the disk drive. The close statement tells Visual Basic not only to close the file, but also to be sure to send all the data from the buffer first Automatic File Closing Although it's important to close your files after accessing them, the truth is that if you don't, Visual Basic will. However, Visual Basic closes all open files only when the program ends normally. Leaving file closing up to Visual Basic is dangerous. If something should happen so that the program doesn’t end normally, Visual Bask can't close the file for you, and you might lose data. Trying it out It's time now to see all this file stuff put to work. To do this, start a new Visual Basic project (a Standard EXE), and place Label, Textbox, and Command Button controls on the form, as shown here: Now, double-click the Command Button control to bring up the code window, and type the following program lines (Visual Basic will have already started the Command1_Click procedure for you): Private Sub Command1_Click() Dim data As String data = Text1.Text Open "c:\MyFile.dat" For Output As #1 Print #1, data Close #1 MsgBox "Text saved." End Sub Private Sub Form_Load( ) Label1.Caption = "Enter the text to file:" Text1.Text = "Default text" Command1.Caption = "Save Text" End Sub After typing the lines, save your work, and run the program. When you do, the application's main window appears, which looks like this: Type whatever text you want into the text box (or just leave the default text as is), and click the Save Text button. Visual Basic saves the contents of the text box to a file named MyFile.dat. This happens in the Commandl_Click procedure, the first line of which declares a string variable: Dim data As String After declaring the variable, the program sets the variable to the text in the Textbox control: data = Text1.Text Next comes the old familiar Open statement, which opens the file for output: Open “c:\MyFile.dat” For Output As #1 With the file open, the program can save the contents of the variable data to the file: Print #1, data Finally, the program closes the file and displays a message box that informs the user that the text was saved: Close #1 MsgBox "Text saved." The thing to notice about this program is that rather than having the Print statement save a string literal as was done previously, this Print statement saves the contents of a string variable. Visual Basic can save a string to the file either way, without, the slightest bit of whining. Loading Data from a File Your file now has data in it. What that data actually is depends on what you typed into the text box before clicking the Save Text button. Data in a file, however, is about as useful as a clock to a goldfish if you have no way of getting the data out again, that's where the Input statement comes in handy. Luckily, you're about to see how that works. Go back to the program you just worked on and add another Command Button control, like this: Now add the following line to the Form_Load procedure (it can go anywhere in the procedure): Command2.Caption = "Load Text" Finally, double-click the new button to display the code window. Visual Basic will start the Command2_Click procedure for you. Add the lines needed to make the procedure look as follows: Private Sub Command2_Click( ) Dim data As String Open "c:\MyFile.dat" For Input As #1 Input #1, data Close #1 Textl.Text = data End Sub You're now ready to try the program out again. Save your work and run the program. When the program's window appears, clear all the text from the text box, and click the Load Text button. When you do, the program gets the text you saved to the file and displays it in the text box. How does this program work? When you click the Load Text button, Visual Basic jumps to the Command2_Click procedure, the first line of which declares a string variable: Dim data As String After declaring the variable, the program opens the file for input: Open "c:\MyFile.dat' For Input As #1 With the file open, the program can now load the text from the file and into the string variable data: Input #1, data Finally, the program closes the file and displays the loaded text in the text box: Close #1 Textl.Text = data Notice that the Input statement looks a lot like the Print statement. That is, the file number, a comma, and the variable name follow the Input keyword. In this case, though, the variable receives the data rather than holding the data that will go to the file. Appending Data to a File Every time you click the Save Text button, and the program opens the MyFile.dat file for output, the previous contents of the file get erased like a teacher's chalkboard at the end of the day. This is all fine and dandy if you want to start a new file, but what. if you want to add something to the file? Easy! You open the file in Append mode. To check this out, add yet another Command Button control to your program, so that the form looks like this: Now add the following line to the Form_Load procedure (it can go anywhere in the procedure): Command3.Caption = "Append Text" Finally, double-click the new button to display the code window. Visual Basic will start the Command3_Click procedure for you. Add the lines needed to make the procedure look as follows: Private Sub Command3_Click() Dim data As String data = Text1.Text Open “c:\MyFile.dat” For Append As #1 Print #1, data Close #1 MsgBox "Text saved." End Sub This procedure is almost exactly like Commandl_Click, except it opens the file in Append mode, rather than in output mode. Finally, because your file will have more than one line of text in it after the append, the program needs to change the way it inputs data from the file. Specifically, the program needs to keep loading text strings until it gets to the end of the file. To do this, replace the current Command2_Click procedure with the following revised procedure: Private Sub Command2_Click() Dim data As String Open "c:\MyFile.dat" For Input As #1 Do While Not EOF(1) Input #1, data MsgBox data Loop Close #1 End Sub Now, save your work and run the program. When the main window appears, type some text into the text box, and then click the Append Text button. Visual Basic saves the text immediately after the text that's already in the file. You can save as many text strings as you like by continuing to change the text in the text box and clicking the Append Text button. When you click the Load Text button, the program no longer displays the text in the text box, because there is more than one line of text in the file. Instead, the program loads a line of text, and displays it in a message box. Each time you dismiss the message box, another one appears with the next line of text. This process continues until the program reaches the end of the file. How does the program know when it's reached the end of the file? The secret to that little mystery lies in the revised Command2_Click procedure. The procedure opens the file for input as you would expect, but then it starts a Do While loop, the first line of which looks like this: Do While Not EOF(1) You already know what a Do While loop is, and you know what the Not operator does, but what's that EOF (1)? EOF is a function that equals the value True when the file is at the end and False if the file is not at its end. (Programmers say the function returns the value True or False.) The number in the parentheses is the number assigned to the file in the Open statement. Basically, the first line of the Do While can be translated into English as "Do while file #1 is not at the end of the file." Inside the loop, the program loads and displays a line of text: Input #1, data Msgbox data Then the Loop keyword sends Visual Basic back to the beginning of the loop, where the function EOF again checks for the end of the file. If the program hasn't reached the end of the file yet, the loop loads another line of text; otherwise, the loops ends. Strings, Integers, and More In this chapter, you've used files only to save text data. However, you can use the file-handling techniques you've learned to save most kinds of data to a file, including integers and floating-point values. For example, if you have an integer variable called myInt, you can save it to an open file with a line like Print #1, myInt. Summary Accessing a file requires three steps: Opening the file, saving or loading data to or from the file, and closing the file. The Open statement opens a file in one of five modes. Those modes are Append, Binary, Input, Output, and Random. Currently, you don't need to know about Binary and Random files; they're for more advanced programmers. The Print # statement stores data in an open file. The Input # statement loads data from an open file. When a program finishes with a file, it must close the file with the Close statement. Failure to close the file properly could result in lost data. The Output file mode creates the file if it doesn't exist or opens and erases the file if it does exist. The Input file mode enables a program to read data from an existing file. The Append file mode enables a program to add data to an already existing file. The EOF function returns True when the program has reached the end of a file and returns False if the program has not reached the end of the file.