Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to File I/O How to read & write data to a disk file...

Similar presentations


Presentation on theme: "Introduction to File I/O How to read & write data to a disk file..."— Presentation transcript:

1 Introduction to File I/O How to read & write data to a disk file...

2 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 Open the file in VS so the O/S can do the actual reading process Read each line into a temp variable. 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 Add the line we read to a list box Continue reading each line until we reach the end of the file (EOF) Continue reading each line until we reach the end of the file (EOF) Close the file. Close the file. Each file needs an ID called a Handle and it acts as a buffer when data is read from disk Each file needs an ID called a Handle and it acts as a buffer when data is read from disk

3 Here is the code Lets create a temp variable to hold our line of data: Dim myData as String 2. Open the file: FileOpen(FileNum, FileName, OpenMode) FileOpen(1, A:\Products.Txt, OpenMode.Input)Input = Read! 3. 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 4. Close the file 5. FileClose(1) file number 1

4 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 Open the file in VS so the O/S can do the actual writing process Read each line of data in the list box Read each line of data in the list box Write the line we read to our disk Write the line we read to our disk Continue reading each item in the List Box until we reach the end Continue reading each item in the List Box until we reach the end Close the file. Close the file. Remember to make sure we use the same file handle in our code! Remember to make sure we use the same file handle in our code!

5 Here is the code Lets create a temp variable to count the items in the list box: Dim x as Integer 2. Open the file: FileOpen(FileNum, FileName, OpenMode) FileOpen(2, A:\Products.Txt, OpenMode.Output) Output mode: creates file if it needs to and writes data If 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 3. 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 4. Close the file 5. FileClose(2) file number 2


Download ppt "Introduction to File I/O How to read & write data to a disk file..."

Similar presentations


Ads by Google