Cambridge A & AS Level Computer Science 9618 Files
Paper 2: Fundamental Problem-Solving And Programming Skills
10 Data Types And Structures
10.3 Files
Why are files needed?
Computer programs read, modify and manipulate / process data. But as soon as a program shuts
down, whatever data it held in main memory (RAM) is gone.
However, the data often needs to be kept for use by the same program or another program at
some point in the future. For this to happen, the data needs to be stored in secondary memory i.e.
hard disk or other storage medium. To do this, the data is stored in a file.
So the reasons why a program might need to store data in a file:
• Data is not lost when the computer is switched off (i.e. data is stored permanently).
• Data can be used by more than one program or reused when a program is run again.
• Data can be backed up or archived.
• Data can be transported from one place / system to another.
File handling operations
Open / Create file
Every file in secondary storage has its own unique identifier (file name), tied to the memory
locations that hold the file's data.
The command for opening file allows the program to open an existing file. Some programming
languages combine the Open and Create functions, so if the file does not exist, then the
command may create a new file.
Files can be opened in different modes. Each mode allows different tasks to be performed on the
open file. These modes as per the syllabus are:
Prepared by K.Ramkissoon, St Joseph's College 1
Cambridge A & AS Level Computer Science 9618 Files
• READ For data to be read from the file (i.e. retrieve / load data from file which can
be output)
• WRITE For data to be written to the file (i.e. input data to file). A new file will be
created and any existing data in the file will be lost / overwritten.
• APPEND Opens the file for adding to only. Existing data cannot be deleted.
Note: A file should be opened in only one mode at a time.
Pseudocode for opening file in READ mode:
OPENFILE Filename FOR READ
Pseudocode for opening file in WRITE mode:
OPENFILE Filename FOR WRITE
The 'Filename' is the name of the file.
Close file
Files should be closed when they are no longer needed.
Pseudocode for closing file:
CLOSEFILE Filename
Read file
Data is read from the file (after the file has been opened in READ mode). When the command
below is executed, the data item is read and assigned to the variable.
Pseudocode for reading from file:
READFILE Filename, Variable
Prepared by K.Ramkissoon, St Joseph's College 2
Cambridge A & AS Level Computer Science 9618 Files
Write to file
Data is written into the file (after the file has been opened in WRITE mode). When the command
below is executed, the string from the variable is written into the file and the file pointer moves
to the next line.
Pseudocode for writing to file:
WRITEFILE Filename, Variable
The examples that follow use all these operations (i.e. open, close, write, read) together.
Write a line of text to text file and read that line from file
Pseudocode:
DECLARE Lineoftext : STRING // Declare variable Lineoftext
OPENFILE Myfirstfile.txt FOR WRITE // Open file for writing
OUTPUT “Enter line of text: ”
INPUT Lineoftext // Enter text at keyboard
WRITEFILE Myfirstfile.txt, Lineoftext // Write text to file
CLOSEFILE Myfirstfile.txt // Close file after writing
OUTPUT “The file contains this line of text: ”
OPENFILE Myfirstfile.txt FOR READ // Open file for reading
READFILE Myfirstfile.txt, Lineoftext // Read text from file
OUTPUT Lineoftext // Print text on screen
CLOSEFILE Myfirstfile.txt // Close file after reading
Prepared by K.Ramkissoon, St Joseph's College 3
Cambridge A & AS Level Computer Science 9618 Files
Visual Basic:
Dim Lineoftext As String ' Declare variable Lineoftext
Dim Filewriter As IO.StreamWriter ' Declare Filewriter of type StreamWriter
Dim Filereader As IO.StreamReader ' Declare Filereader of type StreamReader
Filewriter = New IO.StreamWriter("Myfirstfile.txt") ' Create / open file for writing
Console.Write("Enter line of text: ")
Lineoftext = Console.ReadLine() ' Enter text at keyboard
Filewriter.WriteLine(Lineoftext) ' Write text to file
Filewriter.Close() ' Close file after writing
Filereader = New IO.StreamReader("Myfirstfile.txt") ' Open file for reading
Console.WriteLine("The line of text is ")
Lineoftext = Filereader.ReadLine() ' Read from file and assign to variable
Console.WriteLine(Lineoftext) ' Output text on screen
Filereader.Close() ' Close file after reading
Note:
• File is accessed through an object called StreamWriter.
• StreamWriter is used for writing characters to a stream.
• “Myfirstfile.text” is the name of the text file.
• StreamReader is used for reading characters from a byte stream.
• If StreamWriter or StreamReader is not preceded by IO (which stands for input/output), then
we must include the statement Imports System.IO above Module Module1 in the code editor
of Visual Studio.
Prepared by K.Ramkissoon, St Joseph's College 4
Cambridge A & AS Level Computer Science 9618 Files
Copy a line of text from FileA.txt to FileB.txt
Pseudocode:
DECLARE Lineoftext : STRING
OPENFILE FileA.txt FOR READ
READFILE FileA.txt, Lineoftext
CLOSEFILE FileA.txt
OPENFILE FileB.txt FOR WRITE
WRITEFILE FileB.txt, Lineoftext
CLOSEFILE FileB.txt
Visual Basic:
Dim Lineoftext As String
Dim Filewriter As IO.StreamWriter
Dim Filereader As IO.StreamReader
Filereader = New IO.StreamReader("FileA.txt")
Lineoftext = Filereader.ReadLine()
Filereader.Close()
Filewriter = New IO.StreamWriter("FileB.txt")
Filewriter.WriteLine(Lineoftext)
Filewriter.Close()
Write and read single items of data
Example: Enter data about name, age, and hobby for some students in a text file and output them if
user has no more data to enter.
Prepared by K.Ramkissoon, St Joseph's College 5
Cambridge A & AS Level Computer Science 9618 Files
Pseudocode:
DECLARE Name, Age, Hobby : STRING
DECLARE Reply : CHAR
OPENFILE Studentinfo.txt FOR WRITE
REPEAT
OUTPUT “Enter name of student: ”
INPUT Name
OUTPUT “Enter age of student: ”
INPUT Age
OUTPUT “Enter hobby of student: ”
INPUT Hobby
WRITEFILE Studentinfo.txt, Name
WRITEFILE Studentinfo.txt, Age
WRITEFILE Studentinfo.txt, Hobby
OUTPUT “Do you wish to enter data about another student? y/n”
INPUT Reply
UNTIL Reply = “n”
CLOSEFILE Studentinfo.txt
OPENFILE Studentinfo.txt FOR READ
OUTPUT “Student info: ”
REPEAT
READFILE Studentinfo.txt, Name
OUTPUT Name
READFILE Studentinfo.txt, Age
OUTPUT Age
READFILE Studentinfo.txt, Hobby
OUTPUT Hobby
UNTIL EOF(Studentinfo.txt) // Read till end of file reached
CLOSEFILE Studentinfo.txt
Note: The function / method EOF() is used to test whether the file pointer is at the end of the file.
It returns a boolean value TRUE if the file pointer is at the end of the file and FALSE otherwise.
Prepared by K.Ramkissoon, St Joseph's College 6
Cambridge A & AS Level Computer Science 9618 Files
Visual Basic:
Dim Name, Age, Hobby As String
Dim Reply As Char
Dim Filewriter As IO.StreamWriter
Dim Filereader As IO.StreamReader
Filewriter = New IO.StreamWriter("Studentinfo.txt")
Do
Console.Write("Enter name of student: ")
Name = Console.ReadLine()
Console.Write("Enter age of student: ")
Age = Console.ReadLine()
Console.Write("Enter hobby of student: ")
Hobby = Console.ReadLine()
Filewriter.WriteLine(Name)
Filewriter.WriteLine(Age)
Filewriter.WriteLine(Hobby)
Console.WriteLine("Do you wish to enter data about another student? y/n")
Reply = Console.ReadLine()
Loop Until Reply = "n"
Filewriter.Close()
Filereader = New IO.StreamReader("Studentinfo.txt")
Console.WriteLine("Student info: ")
Do
Name = Filereader.ReadLine()
Console.WriteLine(Name)
Age = Filereader.ReadLine()
Console.WriteLine(Age)
Hobby = Filereader.ReadLine()
Console.WriteLine(Hobby)
Loop Until Filereader.EndOfStream
Filereader.Close()
Prepared by K.Ramkissoon, St Joseph's College 7
Cambridge A & AS Level Computer Science 9618 Files
Note: EndOfStream gets a value that indicates whether the current stream position is at the end
of the stream.
Appending to file (one line of text)
Pseudocode:
DECLARE Lineoftext : STRING // Declare variable Lineoftext
OPENFILE Myfirstfile.txt FOR APPEND // Open file for appending
OUTPUT “Enter data: ”
INPUT Lineoftext // Enter text at keyboard
WRITEFILE Myfirstfile.txt, Lineoftext // Add text to file
CLOSEFILE Myfirstfile.txt // Close file after appending
Visual Basic:
Sub Main()
Dim Filewriter As IO.StreamWriter
Dim Lineoftext As String
Filewriter = New IO.StreamWriter("Myfirstfile.txt", True)
Console.WriteLine("Enter data:")
Lineoftext = Console.ReadLine()
Filewriter.WriteLine(Lineoftext)
Filewriter.Close()
End Sub
Prepared by K.Ramkissoon, St Joseph's College 8
Cambridge A & AS Level Computer Science 9618 Files
Note:
• The code for append is similar to the one for write.
• But a second parameter 'True' is passed to StreamWriter for the program to know we are
appending and not writing to the file.
Appending to file (several lines of text)
Pseudocode:
DECLARE Lineoftext : STRING
DECLARE Line : INTEGER
DECLARE Numoflines : INTEGER
OPENFILE Myfirstfile.txt FOR APPEND
OUTPUT “Enter number of lines of text to append: ”
INPUT Numoflines
OUTPUT “Enter data: ”
FOR Line ← 1 TO Numoflines
INPUT Lineoftext
WRITEFILE Myfirstfile.txt, Lineoftext
NEXT Line
CLOSEFILE Myfirstfile.txt
Prepared by K.Ramkissoon, St Joseph's College 9
Cambridge A & AS Level Computer Science 9618 Files
Visual Basic:
Sub Main()
Dim Filewriter As IO.StreamWriter
Dim Lineoftext As String
Dim Line, Numoflines As Integer
Filewriter = New IO.StreamWriter("Myfirstfile.txt", True)
Console.WriteLine("Enter number of lines of text to append: ")
Numoflines = Console.ReadLine()
Console.WriteLine("Enter text:")
For Line = 1 To Numoflines
Lineoftext = Console.ReadLine()
Filewriter.WriteLine(Lineoftext)
Next
Filewriter.Close()
End Sub
Example involving array and file
1 Declare a 2D array to store the board data for the game Noughts and Crosses. The empty squares
of the board are to be represented by a space. Player A’s counters are to be represented by “O”.
Player B’s counters are to be represented by “X”.
2 Initialise the array to start with each square being empty.
3 Write a statement to represent player A placing their counter in the top left square.
4 Write a statement to represent player B placing their counter in the middle square.
Index 1 2 3
1 O
2D array Board(3, 3)
2 X
3
Prepared by K.Ramkissoon, St Joseph's College 10
Cambridge A & AS Level Computer Science 9618 Files
5 Write pseudocode to save the array data to a text file.
6 Write pseudocode to read the values stored in the text file back into the board array.
Pseudocode:
DECLARE Board : ARRAY[1:3, 1:3] OF CHAR
DECLARE Board2 : ARRAY[1:3, 1:3] OF CHAR
DECLARE Rowcounter, Columncounter : INTEGER
DECLARE Lineoftext : STRING
DECLARE Rowindex : INTEGER
Rowindex ← 1
FOR Rowcounter ← 1 TO 3 // Initialise 2D array with empty string
FOR Columncounter ← 1 TO 3
Board[Rowcounter, Columncounter] ← “”
Next Columncounter
Next Rowcounter
Board[1, 1] ← “O” // Placing values in array
Board[1, 2] ← “-”
Board[1, 3] ← “-”
Board[2, 1] ← “-”
Board[2, 2] ← “X”
Board[2, 3] ← “-”
Board[3, 1] ← “-”
Board[3, 2] ← “-”
Board[3, 3] ← “-”
OPENFILE Gamefile.txt FOR WRITE // Create/open file for writing
FOR Rowcounter ← 1 TO 3
FOR Columncounter ← 1 TO 3
WRITEFILE Gamefile.txt, Board[Rowcounter, Columncounter]
NEXT Columncounter
OUTPUT “” // Jump to new line in file
NEXT Rowcounter
Prepared by K.Ramkissoon, St Joseph's College 11
Cambridge A & AS Level Computer Science 9618 Files
CLOSEFILE Gamefile.txt // Close file after writing
OPENFILE Gamefile.txt FOR READ // Create/open file for reading
OUTPUT “The contents from file are read to array:”
WHILE NOT EOF(Gamefile.txt)
READFILE Gamefile.txt, Lineoftext
// Extracting each value from line of text to put in 2D array
Board2[Rowindex, 1] ← MID(Lineoftext, 1, 1)
Board2[Rowindex, 2] ← MID(Lineoftext, 2, 1)
Board2[Rowindex, 3] ← MID(Lineoftext, 3, 1)
// Outputting what is being put in 2D array
OUTPUT Board2[Rowindex, 1]
OUTPUT Board2[Rowindex, 2]
OUTPUT Board2[Rowindex, 3]
Rowindex ← Rowindex + 1
ENDWHILE
Prepared by K.Ramkissoon, St Joseph's College 12
Cambridge A & AS Level Computer Science 9618 Files
Visual Basic:
Dim Board(3, 3) As Char
Dim Board2(3, 3) As Char
Dim Rowcounter, Columncounter As Integer
Dim Filewriter As IO.StreamWriter
Dim Filereader As IO.StreamReader
Dim Lineoftext As String
Dim Rowindex As Integer = 1
For Rowcounter = 1 To 3 ' Initialise 2D array with empty string
For Columncounter = 1 To 3
Board(Rowcounter, Columncounter) = ""
Next
Next
Board(1, 1) = "O" ' Placing values in array
Board(1, 2) = "-"
Board(1, 3) = "-"
Board(2, 1) = "-"
Board(2, 2) = "X"
Board(2, 3) = "-"
Board(3, 1) = "-"
Board(3, 2) = "-"
Board(3, 3) = "-"
Filewriter = New IO.StreamWriter("Gamefile.txt") ' Create / open file for writing
For Rowcounter = 1 To 3
For Columncounter = 1 To 3
Filewriter.Write(Board(Rowcounter, Columncounter))
Next
Filewriter.WriteLine("") ' Jump to new line in file
Next
Filewriter.Close() ' Close file after writing
Prepared by K.Ramkissoon, St Joseph's College 13
Cambridge A & AS Level Computer Science 9618 Files
Filereader = New IO.StreamReader("Gamefile.txt") ' Create / open file for reading
Console.WriteLine("The contents from file are read to array:")
While Not Filereader.EndOfStream
Lineoftext = Filereader.ReadLine()
' Extracting each value from line of text to put in 2D array
Board2(Rowindex, 1) = Mid(Lineoftext, 1, 1)
Board2(Rowindex, 2) = Mid(Lineoftext, 2, 1)
Board2(Rowindex, 3) = Mid(Lineoftext, 3, 1)
' Outputting what is being put in 2D array
Console.WriteLine(Board2(Rowindex, 1))
Console.WriteLine(Board2(Rowindex, 2))
Console.WriteLine(Board2(Rowindex, 3))
Rowindex = Rowindex + 1
End While
It is highly recommended to read the whole chapter on Files in the Cambridge International
AS & A Level Computer Science Textbook (by Helen Williams & David Watson).
References
LANGFIELD, S. and DUDDELL, D. (2015) Cambridge International AS and A Level Computer
Science Coursebook. United Kingdom: Cambridge University Press.
LANGFIELD, S. and DUDDELL, D. (2019) Cambridge International AS and A Level Computer
Science Coursebook 2nd ed. United Kingdom: Cambridge University Press.
PIPER, T. (2016) Cambridge International AS and A Level Computer Science Revision Guide.
United Kingdom: Cambridge University Press.
Prepared by K.Ramkissoon, St Joseph's College 14
Cambridge A & AS Level Computer Science 9618 Files
WATSON, D. and WILLIAMS, H. (2019) Cambridge International AS & A Level Computer
Science. London: Hodder Education
Fundamentals of data structures: Fields records and files - Wikibooks, open books for an open
world [WWW] Available from: https://en.wikibooks.org/wiki/A-
level_Computing/AQA/Paper_1/Fundamentals_of_data_structures/Fields_records_and_files
[Accessed 12/01/17]
(2019) Teach ICT A Level OCR CS 11. File Handling [WWW] Teach-ICT.com. Available from:
https://www.teach-
ict.com/2016/A_Level_Computing/OCR_H446/1_2_software/123_intro_programming/procedural/
miniweb/pg11.php [Accessed 06/05/19]
(2019) GCSE Organising data and handling external files. [WWW] Bitesize. Available from:
https://www.bbc.com/bitesize/guides/zywmyrd/revision/2 [Accessed 06/05/19]
Cambridge International Examinations. Cambridge International AS & A Level Computer Science
Pseudocode Guide for Teachers.
Prepared by K.Ramkissoon, St Joseph's College 15