|
|
|
|
Naming a File A file must have a name, so that it can be retrieved from the location where it is stored. That location can be the internal hard drive, in which case the folder containing the file must be specified, or an external storage device such as a floppy disk, Zip drive, or memory stick. It is customary (but optional) for the name to include a program-specific extension, three letters after a dot, that denotes the file's purpose. WORD saves documents with a .doc extension, EXCEL saves sheets with a .wks extension. The file name can be built into the program, or may be provided by the user during program execution. The file name is a string, and includes the location information (e.g., a:\myfile.dat). Eliciting the File Name from the User The simplest way to ask the user to provide a file name is with a label and text box, wherein the user simply types the name (including the location information). It is far more elegant and user-friendly, though, for the program to get the file name in a dialog box. That allows the user to locate the file with visual cues, and also to avoid input errors that might result in an illegal file name. Using the File Dialog Box There are two things we might do with the file dialog box, Open and Save. The same dialog box control is used for both operations, with the programmer setting a parameter to determine which sort of box appears. The dialog box control is not part of the VB6 default set of controls, and so must be added to the toolbox for the current program. This is accomplished by clicking on the Project Menu, then Components..., then the Controls tab. Add the Microsoft Common Dialog Control 6.0 to the toolbox by checking the box to the left, then clicking on OK. After you save the project, the control will always appear in the toolbox for that project. Drag the control onto the form; it is never visible, so it doesn't matter how big it is or where you place it. Coding the file dialog box can be fairly tricky, as there are a lot of options. However, many of them don't matter too much, and what I show here is sufficient. The code below might go in the subroutine associated with the Open ... item in the File Menu. It is designed to read a set of N scores, to be referred to within the program as the array X() from a file with a .dat extension.. On Error GoTo Errorcheck 'Sets
up error Dim Infilename as String CommonDialog1.CancelError = True 'Allows Numfile = FreeFile 'Freefile is an Input #Numfile, Username 'reads
a value Exit sub Saving to a File Information is saved by "printing" it to a file. This code might go in the subroutine associated with the Save As... item in the File Menu. Here, we are saving a set of M scores that had previously been stored publicly in the array Y() into a file with a .dat extension.. Dim Numfile As Long On Error GoTo Saverror 'sets
up error Print #Numfile, Username 'prints
a stored Print #Numfile, Userage 'prints
another |
|
|