Component 9, Slide 1 CP2030 Copyright © University of Wolverhampton CP2030 Visual Basic for C++ Programmers v Component 9 working with text files and random access files
Component 9, Slide 2 CP2030 Copyright © University of Wolverhampton Aims and objectives v Review the use of text files v Understand the structure of Random Access Files (RAF’s) v Use the various techniques available in Visual Basic to write to random access files. v Set the file read and write access for users and second users
Component 9, Slide 3 CP2030 Copyright © University of Wolverhampton Useful functions for handling Drives, Directories and Files v ChDrive - v ChDir- v CurDir$ - v MkDir- v RmDir - v Dir$ -
Component 9, Slide 4 CP2030 Copyright © University of Wolverhampton VB data files v VB supports three kinds of data files – Sequential (text) files store data as ACII text. Characters are read from and stored to the file character by character (see VB1) – Random-access files store data in special VB internal formats. Such files require rigid file structure – Binary files store data as individual bytes. No file structure exists, and no special internal formats are assumed v we will review text files and look at random-access files this week and binary files later in the module
Component 9, Slide 5 CP2030 Copyright © University of Wolverhampton Sequential (Text) files v Commands for handling Text files: v Useful Functions/Statement – FreeFile - – Dir$ - – Tab- – Spc-
Component 9, Slide 6 CP2030 Copyright © University of Wolverhampton Opening Text Files v Before you can use a file you must open it: Opening for Input: Opening for Output: v Opening for Appending:
Component 9, Slide 7 CP2030 Copyright © University of Wolverhampton Using FreeFile We should use FreeFile to ensure we get an unused file handle: Dim iFileNum As Integer ‘get the next free file ‘open the file Open "C:\CISFILE.TXT" For Output As #iFileNum
Component 9, Slide 8 CP2030 Copyright © University of Wolverhampton Closing Files v When we have finished with a file we should close it: Closing a specific file: Close #1 or Close #iFileNum Closing all files: Close v It is good practice to open a file when it is needed and close it again as soon as it is finished with
Component 9, Slide 9 CP2030 Copyright © University of Wolverhampton Checking if a File Already Exists1 If you want to check if a file already exists then the best way to do this is using the Dir$() function: 'check if a normal file exists If Dir$("C:\CISFILE.TXT") <> "" Then MsgBox “The File Exists” 'open the file inside the if exists Open "C:\CISFILE.TXT" For Input As #1 ‘statements 'close the file before leaving the if exists Close #1 Else MsgBox “The File Doesn’t Exist” End If
Component 9, Slide 10 CP2030 Copyright © University of Wolverhampton Checking if a File Already Exists2 v You can also use symbolic file attribute constants: Symbolic ConstantValueMeaning ATTR_NORMAL 0 ATTR_HIDDEN 2 ATTR_SYSTEM 4 ATTR_VOLUME 8 ATTR_DIRECTORY 16 'check if a directory exists If Dir$("C:\CISDIR",ATTR_DIRECTORY) <> "" Then MsgBox “The Sub Directory Exists” End If v You can, of course, combine file attribute constants
Component 9, Slide 11 CP2030 Copyright © University of Wolverhampton Printing To Text Files 1 v Once a file has been opened for Output or Appending we can either Print or Write information to it Print # Statement: Open "TESTFILE.TXT" For Output As #1 Print #1, "Test of the Print # statement" ' Print blank line to file Print #1, ' Print in two print zones iValue = 12 Print #1, ”Value is", iValue ' Print two strings together Print #1, "With no space between" ; "." Close #1
Component 9, Slide 12 CP2030 Copyright © University of Wolverhampton Printing To Text Files 2 v File: v Notice effects of “,” and “;” in layout of fields
Component 9, Slide 13 CP2030 Copyright © University of Wolverhampton Printing To Text Files - Tab Function v There are two functions available which can help the programmer with formatting the layout of a file when using Print # Tab function: Open "TEST2.TXT" For Output As #1 Print #1,"This is a Tab";Tab(20);"function test." Print #1, "Get the"; Tab(20); "idea?" Close #1 File: This is a Tab function test. Get the idea?
Component 9, Slide 14 CP2030 Copyright © University of Wolverhampton Printing To Text Files Spc Function Spc function: ' open file for output Open "TEST3.TXT" For Output As #1 Print #1, "This is a Spc function”;Spc(10);"test." ' close file Close #1 File: This is a Spc function test.
Component 9, Slide 15 CP2030 Copyright © University of Wolverhampton Line Input From Text Files 1 Line Input # is the 'opposite' of Print #, as it reads everything that is on the line in the file: Dim sInBuffer As String Open "C:\TESTFILE.TXT" For Input As #1 Line Input #1, sInBuffer Label1.Caption = sInBuffer + chr(13) Line Input #1, sInBuffer Label1.Caption = Label1.Caption + sInBuffer + chr(13) Line Input #1, sInBuffer Label1.Caption = Label1.Caption + sInBuffer + chr(13) Line Input #1, sInBuffer Label1.Caption = Label1.Caption + sInBuffer + chr(13) Close #1
Component 9, Slide 16 CP2030 Copyright © University of Wolverhampton Line Input From Text Files 2 TESTFILE.TXT Test of the Print # statement Value is 12 With no space between. Label1.Caption = Test of the Print # statement Value is 12 With no space between. v Note: Data is read line-by-line; not as separate fields
Component 9, Slide 17 CP2030 Copyright © University of Wolverhampton Line Input From Text Files: EOF Function If we don't know how many lines there are in a file then we can loop and use the EOF() function to check for the end of the file: Dim sInBuffer As String ‘open the file Open "C:\TEST3.TXT" For Input As #1 ‘blank the label to start with Label1.Caption = "" ‘while it’s not the end of file While Not EOF(1) ‘get line & place in label Line Input #1, sInBuffer Label1.Caption = Label1.Caption +sInBuffer +chr(13) Wend Close #1 ‘close the file
Component 9, Slide 18 CP2030 Copyright © University of Wolverhampton Line Input From Text Files 3 v Looping while it isn’t the end of file produces the same results as before: TEST3.TXT This is a sample text file which contains four lines! Label1.Caption = This is a sample text file which contains four lines!
Component 9, Slide 19 CP2030 Copyright © University of Wolverhampton Writing To Text Files 1 v For a file which has been opened for Output or Appending we can use Write instead of Print Write # Statement: Open ”U:\TESTFILE.TXT" For Output As #1 Write #1,"This is a test of the Write # statement." ' Write blank line to file Write #1, ' Write three fields on the same line iValue = 12 Write #1,"Numbers ", iValue; 20 Write #1,"End Test" Close #1
Component 9, Slide 20 CP2030 Copyright © University of Wolverhampton Writing To Text Files 2 The file produced looks like: v Note that the blank line has nothing on it; also semi-colon separator replaced by comma v Compare this with the file created by Print # v User-defined data types cannot be written in one piece; they must be written to file as separate fields
Component 9, Slide 21 CP2030 Copyright © University of Wolverhampton Input #… reading back from a file created with Write # Dim sInBuffer As String Dim iVal1 As Integer, iVal2 As Integer Open "U:\TESTFILE.TXT" For Input As #2 Input #2, sInBuffer label1.Caption = sInBuffer Input #2, sInBuffer, iVal1, iVal2 label1.Caption = label1.Caption + Chr(13) + sInBuffer label1.Caption = label1.Caption + Str(iVal1) + " + " + Str(iVal2) + " = " label1.Caption = label1.Caption + Str(iVal1 + iVal2) + Chr(13) Input #2, sInBuffer label1.Caption = label1.Caption + Chr(13) + sInBuffer Close #2
Component 9, Slide 22 CP2030 Copyright © University of Wolverhampton Input From Text Files 2 TESTFILE.TXT "This is a test of the Write # statement." "Numbers",12,20 "End Test" Label1.Caption This is a test of the Write # statement. Numbers = 32 End Test Note: format of the written text file, and how each field has to be read in separately.
Component 9, Slide 23 CP2030 Copyright © University of Wolverhampton Random Access Files v In a Sequential File, a particular record may only be accessed by reading sequentially through the file, from the beginning v In a Random Access file, a particular record may be accessed directly, without reading all preceding records. v A Random Access file is like an array of records, but stored on disk. v Random Access files are also known as Direct Access or Relative files.
Component 9, Slide 24 CP2030 Copyright © University of Wolverhampton File structure v All records in a Random Access file must be the same size. v Each record has a unique record number; representing its location in the file. v Using the record length and the record number a particular record can be located directly v Records typically are created using a user-defined type.
Component 9, Slide 25 CP2030 Copyright © University of Wolverhampton Steps to process a RAF Use the following four steps to process RAFs with record variables 1 define a record variable matching your data template 2 open the File For Random 3 Use a record variable in Get and Put instructions to read and write the data 4 Close the file
Component 9, Slide 26 CP2030 Copyright © University of Wolverhampton Random Access Files and User Defined Types v User defined types lend themselves ideally to use with random access files as they have a set number of elements in each record v take a file for holding info. on a stamp collection as an example. We will store the information as shown, with the size of each data field being fixed by the user or by the data type used
Component 9, Slide 27 CP2030 Copyright © University of Wolverhampton 1st Step to process the RAF 1define a user defined type matching your data template v in our case it will look like Type Stamptype iYear as integer sCountry as string * 18 ‘ max string length 18 fValue as single sComment as string * 60 ‘ max string length 60 End Type Dim uStamp as Stamptype
Component 9, Slide 28 CP2030 Copyright © University of Wolverhampton 2nd step - opening the file 2.A random access file can only be opened as Random, unlike the sequential file where Append, Input and Output can be used. v The syntax is as follows: Open filename For Random As #filenum Len = recordlength where filename is the filename and path #filenum is the filehandle number recordlength is the number of bytes in the record e.g. applying this to our stamp collection database Open “c:\temp\stamp.ran” For Random As #1 Len = 84
Component 9, Slide 29 CP2030 Copyright © University of Wolverhampton Length of user-defined data type v To save you having to work out the length of your data type you can use the Len(..) function Dim uStamp as StampType Open “c:\temp\stamp.ran” For Random As #1 Len = Len(uStamp)
Component 9, Slide 30 CP2030 Copyright © University of Wolverhampton 3rd step - writing and reading records v We can use the Put statement to write to a random file record v It has the form Put #filenum, recordnum, variable in our stamp collection example this would be: Put #1, 12, stamp - recordnum is optional - default is the one after last record written to
Component 9, Slide 31 CP2030 Copyright © University of Wolverhampton 3rd step Reading from a RAF use the Get statement Get #filenum, recordnum, variable in our stamp collection example this would be: Get #1, 12, stamp - where stamp specifies the Variable to receive the data - again recordnum is optional - default is the one after last record read from
Component 9, Slide 32 CP2030 Copyright © University of Wolverhampton More info on Recordnum v As the file is random access - recordnum can be any value above 0. v You can Put data to record number 12 when you have only written data records 1 to 4 previously. v You can Get data from any existing record by specifying its number
Component 9, Slide 33 CP2030 Copyright © University of Wolverhampton 4th step - closing the file As with all file handling work it is important to Close the file when all i/o activity has finished format Close #filenum e.g. Close #1
Component 9, Slide 34 CP2030 Copyright © University of Wolverhampton Seek function v If you have a complex programme and it is difficult to keep track of what record was last written to or read from - use the Seek function which returns the number of the record after the last one you have either written to or read from. Format Seek (filenum) - where the # sign is omitted e.g iNextRecordToOpen = Seek(1)
Component 9, Slide 35 CP2030 Copyright © University of Wolverhampton Seek Statement v Seek statement sets the file pointer to the next record you want to read or write to Format Seek filenum, recordnum, After this Seek a Get or Put statement without a recordnum parameter operates on this newly reset file position e.g Seek #9, 23 ‘ move pointer to the 23rd record of file number 9 Put #9,, uStamp ‘ write the data from uStamp in the 23rd record ‘ of file number 9
Component 9, Slide 36 CP2030 Copyright © University of Wolverhampton Opening files in a network environment v On a network two users running independently may want to open a specific file at the same time. VB offers some control as to the scope of file sharing privileges. v The Open statement allows the setting of these access permissions for the user using the Access clause Format Open filespec For Random Access accessmode lockmode As #Filenum Len = recordlength where accessmode has the options of: Read - read only Write - write only Read Write - read and write
Component 9, Slide 37 CP2030 Copyright © University of Wolverhampton Opening files in a network environment - cont. lockmode - specifies the type of access that other users have to the open file. Has the options of :- (default) if lockmode not specified only one user can open file at a time Shared Multiple users can open the file jointly Lock Read No other user can read from the file Lock Write No other user can write to the file Lock Read Write No other user can access the file e.g Open “c:\temp\stamp.ran” For Random Access Read Lock Read As #1 Len = 84 Here the file is opened as read only and no other can read it at the same time
Component 9, Slide 38 CP2030 Copyright © University of Wolverhampton Summary v We have investigated – the file structure of the Random file type – how we can map reading and writing to a random file using user defined types with the Get and Put statement – the use of the Seek function and statement to point to a particular record or return the next record number to write to or read from – how to set the access rights for users and second users