Cs Abc123 Xyz BDC A1 A2 All Cs
Cs Abc123 Xyz BDC A1 A2 All Cs
Computer Science 9618 10.3) FILES (Using Text Files) Computer Science 9618 10.3) FILES (Using Text Files) Computer Science 9618 10.3) FILES (Using Text Files) Computer Science 9618
with Majid Tahir with Majid Tahir with Majid Tahir with Majid Tahir
Syllabus Content: Or you can write lines in File like this too
PSEUDOCODE: PROCEDURE MakeNewFile (OldFile, NewFile, Status : STRING)
OPENFILE “file.txt” FOR WRITE // open the file for reading DECLARE Line1, Line2, Line3 : STRING
10.3 Files WRITEFILE “file.txt” , “Good Morning” // write a line of text to the file OPENFILE <filename> FOR APPEND // opens the file for read DECLARE NumCopied, NumRecs : INTEGER
show understanding of why files are needed WRITEFILE “file.txt” , “Good Day” WRITEFILE <filename >, <stringValue> // write a line of text to the file NumRecs ← 0
use Pseudocode for file handling: WRITEFILE “file.txt” , “Good night” CLOSEFILE // close file NumCopied ← 0
o OPENFILE <filename> FOR READ/WRITE/APPEND // Open file CLOSEFILE “file.txt” // close file OPENFILE OldFile FOR READ
(understand the difference between various file modes) OPENFILE NewFile FOR WRITE
o READFILE <filename>,<string> // Read a line of text from the file PSEUDOCODE: DECLARE line1, line2, line3 : STRING // declaration of variables WHILE NOT EOF(OldFile)
o WRITEFILE <filename>,<string> // Write a line of text to the file READFILE OldFile, Line1
CLOSEFILE <filename> // Close file OPENFILE <filename> FOR READ // opens the file for read OPENFILE “file.txt” FOR APPEND // open the file for appending/editing
WRITEFILE <filename >, <stringValue> // write a line of text to the file READFILE OldFile, Line2
o EOF(<filename>) // function to test for the end of the file READFILE OldFile, Line3
CLOSEFILE // close file line1 = “Sunday”
Write pseudocode to handle text files that consist of one or more lines NumRecs ← NumRecs + 1
line2 = “Monday”
IF Line3 <> Status THEN
line2 = “Tuesday”
WRITEFILE NewFile, Line1
DECLARE line1, line2, line3 : STRING // no need to re-declare variables in OPENFILE, just
use value of variable to output on screen during OPENFILE operation. WRITEFILE “file.txt” , line1 // write a line of text to the file WRITEFILE NewFile, Line2
WRITEFILE “file.txt” , line2 WRITEFILE NewFile, Line3
OPENFILE “file.txt” FOR READ // open the file for reading WRITEFILE “file.txt” , line2 NumCopied ← NumCopied + 1
10.3 Files WHILE NOT EOF (“file.txt”) END IF
READFILE “file.txt” , line1 // write a line of text to the file CLOSEFILE “file.txt” // close file END WHILE
Data need to be stored permanently. One approach is to use a file. For example, any data held READFILE “file.txt” , line2 OUTPUT "File " , OldFile , " contained " , NumRecs ,__ " employee details"
in an array while your program is executing will be lost when the program stops. You can save READFILE “file.txt” , line2 OUTPUT Numcopied , " employee sets of details were __ written to file", NewFile
the data out to file and read it back in when your program requires it on subsequent executions. END WHILE The end-of-file (EoF) marker CLOSEFILE OldFile
CLOSEFILE “file.txt // close file CLOSEFILE NewFile
If we want to read a file from beginning to end we can use a conditional loop. Text files contain a END PROCEDURE
A text file consists of a sequence of characters formatted into lines. Each line is terminated by special marker at the end of the file that we can test for. Testing for this special end-of- file
an end-of-line marker. Or marker is a standard function in programming languages. Every time th is function is called it will
The text file is terminated by an end-of-file marker. test for this marker.
Accessing special Folders in VB
Note: you can check the contents of a text file (or even create a text file required by a program) DECLARE line1, line2, line3 : STRING // variables already been declared during WRITEFILE Locations of files can vary from machine to machine or user to user. The exact location of my
// no need to re-declare variables in OPENFILE, just use The function will return FALSE if the end of the file is not yet reached and will return TRUE if the
by using a text editor such as NotePad. Documents folder changes depending on who has logged on.
value of variable to output on screen during OPENFILE operation. end -of-file marker has been reached. In pseudocode we call this function EOF(). We can use
VB.net uses special system variables to hold the current users file locations, such as my
the construct REPEAT ... UNTIL EOF().
PSEUDOCODE: documents, desktop, My Music, etc.
OPENFILE “file.txt” FOR READ // open the file for reading To get access to the variables, you must import the system.environment library.
If it is possible that the fi le contains no data, it is better to use the construct WHILE NOT EOF()
OPENFILE <filename> FOR WRITE // open the file for writing
WHILE NOT EOF (“file.txt”) NOTE: Not all locations are available due to system security
WRITEFILE <filename >, <stringValue> // write a line of text to the file For example, the following pseudocode statements read a text file and output its contents:
READFILE “file.txt” Option Explicit On
CLOSEFILE // close file
OUTPUT line1 // write a line of text to the file Imports System.Environment
READFILE “file.txt” Module Module1
DECLARE line1, line2, line3 : STRING OPENFILE "Test .txt" FOR READ Dim mydocs As String
OUTPUT line2
OPENFILE “file.txt” FOR WRITE // open the file for reading Dim mymusic As String
READFILE “file.txt” WHILE NOT EOF("Test.txt")
WHILE NOT EOF “file.txt” Dim myfavorites As String
OUTPUT line2 READFILE "Test. txt", TextString
INPUT line1 Sub main()
END WHILE OUTPUT TextString mydocs = GetFolderPath(SpecialFolder.MyDocuments)
INPUT line2
CLOSEFILE “file.txt” // close file ENDWHILE mymusic = GetFolderPath(SpecialFolder.MyMusic)
INPUT line3
myfavorites = GetFolderPath(SpecialFolder.Favorites)
WRITEFILE “file.txt” , line1 // write a line of text to the file CLOSEFILE "Test. txt"
Console.WriteLine(mydocs)
WRITEFILE “file.txt” , line2 Console.WriteLine(mymusic)
WRITEFILE “file.txt” , line3 Console.WriteLine(myfavorites)
END WHILE Console.ReadLine()
CLOSEFILE “file.txt” // close file End Sub
www.majidtahir.com Contact: 03004003666 Email: [email protected] www.majidtahir.com Contact: 03004003666 Email: [email protected] www.majidtahir.com Contact: 03004003666 Email: [email protected] www.majidtahir.com Contact: 03004003666 Email: [email protected]
1 2 3 4
10.3) FILES (Using Text Files) Computer Science 9618 10.3) FILES (Using Text Files) Computer Science 9618 10.3) FILES (Using Text Files) Computer Science 9618 10.3) FILES (Using Text Files) Computer Science 9618
with Majid Tahir with Majid Tahir with Majid Tahir with Majid Tahir
The first step in working with files in Visual Basic is to open the file. Module module1
Module Module1 Sub Main()
This is achieved using the Visual Basic FileStream class. The FileStreamconstructor accepts the Sub Main() Dim textFileStream As New IO.FileStream("E:\test.txt", IO.FileMode.OpenOrCreate,
file name to be opened as the first parameter, followed by a number of other parameters defining the Dim textFileStream As New IO.FileStream("E:\test.txt", IO.FileMode.OpenOrCreate, IO.FileAccess.ReadWrite, IO.FileShare.None)
mode in which the file is to be opened. These fall into the categories IO.FileAccess.ReadWrite, IO.FileShare.None)
of FileMode, FileAccess and FileShare. The options available as listed in the following tables: textFileStream.Close() Dim myFileWriter As New IO.StreamWriter(textFileStream)
End Sub Dim intCounter As Integer
FileMode Options End Module
For intCounter = 0 To 10
This code will create a text file in E drive with the name test.txt myFileWriter.WriteLine("This is line " & CStr(intCounter))
Next intCounter
myFileWriter.Close()
textFileStream.Close()
End Sub
End Module
Creating CSV files with WRITELINE NOTE: Strings are enclosed in quotes, numbers are not enclosed in quotes
For other ways of manipulating CSV files, see page 82
The comma-separated values (CSV) file format is a file formats used to store tabular data in which
numbers and text are stored in plain textual form that can be read in a text editor, spreadsheet or
Database.
Lines in the text file represent rows of a table, and commas in a line separate what are fields in the tables Writing to a text file
row.
The following example used the WriteLine statement to create a CSV file with 3 variables:
Writing to a text file usually means creating a text file.
Module module1 The following code examples demonstrate how to open, write to and close a file called
Sub Main() sampleFile.TXT in each of the three languages. If the file already exist s, it is overwritten as
Dim Field1 As String soon as the file handle is assigned by the 'open file' command.
Dim Field2 As Integer
Dim field3 As Double
Field1 = "Some Text"
field2 = 7
www.majidtahir.com Contact: 03004003666 Email: [email protected] www.majidtahir.com Contact: 03004003666 Email: [email protected] www.majidtahir.com Contact: 03004003666 Email: [email protected] www.majidtahir.com Contact: 03004003666 Email: [email protected]
5 6 7 8
10.3) FILES (Using Text Files) Computer Science 9618 10.3) FILES (Using Text Files) Computer Science 9618 10.3) FILES (Using Text Files) Computer Science 9618 10.3) FILES (Using Text Files) Computer Science 9618
with Majid Tahir with Majid Tahir with Majid Tahir with Majid Tahir
Module module1
OPENFILE <filename> FOR READ // open the file for reading
Sub main() READFILE <filename >, <stringValue> // read a line of text to the file
Dim FileHandle As IO.StreamWriter 'The file is accessed th ro ugh an object (see CLOSEFILE // close file
Dim LineOfText As String 'called a StreamWriter. Printing a line of text
FileHandle = New Reading From a File in Visual Basic
IO.StreamWriter("SampleFile . TXT")
The PrintLine writes a string to a text file
FileHandle.WriteLine(LineOfText)
opened with a filenumber. Now that we have created and written to a file the next step is to read some data from the file. This is
FileHandle.Close()
achieved using the Visual Basic StreamReader object.
End Sub
End Module
StreamWriter with text files The StreamReader ReadLine() method can be used to read the next line from the file stream including
Reading a line of text the new line. The Read() method reads a line from the file but removes the new line.
Two objects StreamReader and StreamWriter are used to read and write data in a text file. The ReadToEnd() method can be used to read from the current line in the file to the end of the file.
Both of these commands are stored in the System.IO library, so you will need to import it into To read a line of text from the opened file
The following code excerpt further extends our example to read the data back from the file after it has
your program. been written and display the contents in a MessageBox:
The following line needs to be added B System.IO by adding before the Module definition
Dim textFileStream As New IO.FileStream("E:\test.txt", IO.FileMode.OpenOrCreate,
IO.FileAccess.ReadWrite, IO.FileShare.None)
Option Explicit On Dim myFileWriter As New IO.StreamWriter(textFileStream)
Imports System.IO Dim myFileReader As New IO.StreamReader(textFileStream)
Dim intCounter As Integer
Imports System.Environment Writing a line of text Dim strFileContents As String
Module module1
'create a variable to write a stream of characters to a text file For intCounter = 0 To 10
The Writeline writes to a textfile opened with a filenumber BUT the string is enclosed in quotes myFileWriter.WriteLine("This is line " & CStr(intCounter))
Dim CurrentFileWriter As StreamWriter
Sub Main() Next intCounter
Dim FileName, TextString As String
Closing file strFileContents = myFileReader.ReadToEnd()
Dim Count As Integer MsgBox(strFileContents)
FileName = GetFolderPath(SpecialFolder.MyDocuments) & "text.txt" myFileWriter.Close()
CurrentFileWriter = New StreamWriter(FileName) myFileReader.Close()
Console.WriteLine("File being created") textFileStream.Close()
CurrentFileWriter.WriteLine("File ceated on " & Now())
For Count = 1 To 5
TextString = Rnd() * 100
Console.WriteLine("Random number " & Count & " is " & TextString)
CurrentFileWriter.WriteLine("Random number " & Count & " is " & TextString) Writing a line of Text
Next
CurrentFileWriter.Close() ' close file
Console.WriteLine("File saved")
Console.ReadLine()
End Sub
End Module
www.majidtahir.com Contact: 03004003666 Email: [email protected] www.majidtahir.com Contact: 03004003666 Email: [email protected] www.majidtahir.com Contact: 03004003666 Email: [email protected] www.majidtahir.com Contact: 03004003666 Email: [email protected]
9 10 11 12
10.3) FILES (Using Text Files) Computer Science 9618 10.3) FILES (Using Text Files) Computer Science 9618
with Majid Tahir with Majid Tahir
www.majidtahir.com Contact: 03004003666 Email: [email protected] www.majidtahir.com Contact: 03004003666 Email: [email protected]
13 14