100 likes | 208 Views
Text and Binary Files. Reading and Writing. Making data persistent. When a program finishes, the data stored in variables is lost. Data can be stored in several ways. Text files csv files Binary files Databases. What you need to know. csv files what it is
E N D
Text and Binary Files Reading and Writing Comp1 notes
Making data persistent • When a program finishes, the data stored in variables is lost. • Data can be stored in several ways. • Text files • csv files • Binary files • Databases Comp1 notes
What you need to know • csv files • what it is • to read records from a csv file • to write records to a csv file • data files • what it is • to read records from a data file • to write records to a data file Comp1 notes
What is a csv file? • Printable characters • Separator between values • Comma • Tab & others are sometimes used • End of line marker Use a spreadsheet and save as csv to make a csv file quickly Comp1 notes
Writing to a text file • Must include IO library Imports System.IO • Declare a writing channel Dim CFW As StreamWriter • Link the file pathname to the channel Filename = “C:\My files\myCsvFile.txt” CFW = New StreamWriter(Filename) • Write a line of text to the channel CFW.WriteLine(“This is a string of text”) • Close the channel CFW.Close() Comp1 notes
Writing to a csvfile • Create a string, using a comma to separate the fields Textstring = (Name & “,” & Telno & “,” & AvPtSc) • Write the string to the file CFW.WriteLine(Textstring) Comp1 notes
Reading from a text file • Must include IO library Imports System.IO • Declare a writing channel Dim CFR As StreamReader • Link the file pathname to the channel Filename = “C:\My files\myCsvFile.txt” CFR = New streamReader(Filename) • Read a line of text from the channel MyString = CFR.ReadLine() • Checkfor end of file CFR.EndOfStream ‘returns boolean • Close the channel CFR.Close() Comp1 notes
Reading from a csv file • You don’t need to know how to use classes to handle csv files. • You do need to know how to handle string functions such as: • length • position • substring • concatenation Comp1 notes
Your mission • Use your Student Record and Student Group array from last lesson • Add five Students • Create a csv file • Write code to write your students to the file • Open your file in a spreadsheet to check • Add 5 more students to the spreadsheet • Write code to read these back into your program as student records and output the whole group to the console window. Comp1 notes