50 likes | 154 Vues
This guide provides a comprehensive overview of file input/output (I/O) operations in Visual Studio. Learn how to read data from a text file into a ListBox and write data back to a disk file. It covers essential steps like opening files, reading lines sequentially, managing file handles, and writing data efficiently. The tutorial includes sample code snippets for both reading and writing processes, ensuring a clear understanding of how to handle file operations correctly, including the use of input and output modes.
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