50 likes | 147 Views
Introduction to File I/O. How to read & write data to a disk file. Steps for Reading a Text File and Filling a List Box. Open the file in VS so the O/S can do the actual reading process Read each line into a temp variable. Text files must be read sequentially
E N D
Introduction to File I/O How to read & write data to a disk file...
Steps for Reading a Text File and Filling a List Box... • Open the file in VS so the O/S can do the actual reading process • Read each line into a temp variable. • Text files must be read sequentially • You cannot open a file and tell O/S to go to line 24 and read the contents. • Add the line we read to a list box • Continue reading each line until we reach the end of the file (EOF) • Close the file. • Each file needs an ID called a Handle and it acts as a buffer when data is read from disk
Here is the code... • Let’s create a temp variable to hold our line of data: Dim myData as String • Open the file: FileOpen(FileNum, FileName, OpenMode) FileOpen(1, “A:\Products.Txt”, OpenMode.Input) ‘Input = Read! • Read each line inside a loop: Do Until EOF(1) ‘make sure file numbers match! myData = LineInput(1) ‘file number 1 lbItems.Items.Add(myData) Loop • Close the file • FileClose(1) ‘file number 1
Steps for Writing Data From the List Box to the file... • Open the file in VS so the O/S can do the actual writing process • Read each line of data in the list box • Write the line we read to our disk • Continue reading each item in the List Box until we reach the end • Close the file. • Remember to make sure we use the same file handle in our code!
Here is the code... • Let’s create a temp variable to count the items in the list box: Dim x as Integer • Open the file: FileOpen(FileNum, FileName, OpenMode) FileOpen(2, “A:\Products.Txt”, OpenMode.Output) Output mode: creates file if it needs to and writes dataIf the file exists, it will ERASE ALL DATA AND ADD NEW STUFF!!!!Append Mode: creates file if it does not exist and ADDS data If the file already exists, it adds the new data to the end of the file • Read each item in the list box: For x = 0 to lbItems.Items.Count - 1 PrintLine(2, lbItems.Items(x)) ‘file number 2 Next x • Close the file • FileClose(2) ‘file number 2