File handling (Cambridge (CIE) AS Computer Science): Revision Note
Exam code: 9618
Purpose of files
What is file handling?
File handling is the use of programming techniques to work with information stored in text files
Examples of file handing techniques are:
opening text files
reading text files
writing text files
closing text files
Concept | CIE A Level Pseudocode |
|---|---|
Open file for reading |
|
Open file for writing |
|
Close file |
|
Read line |
|
Write line |
|
Check end of file |
|
Create new file |
|
Append to file |
|
An example program written in pseudocode to:
Opens a text file for reading
Reads each line (a fruit name)
Counts how many fruits are in the file
Outputs the total
Closes the file
DECLARE FruitName : STRING
DECLARE FruitCount : INTEGER
FruitCount ← 0
OPENFILE FruitFile FOR READ
WHILE NOT EOF(FruitFile) DO
READFILE FruitFile, FruitName
FruitCount ← FruitCount + 1
ENDWHILE
CLOSEFILE FruitFile
OUTPUT "Total number of fruits: ", FruitCountIdentifier table
Identifier | Data type | Description |
|---|---|---|
| STRING | Stores the name of each fruit read from the file |
| INTEGER | Keeps track of how many fruits have been read |
| FILE | The file containing the fruit names (e.g. "fruit.txt") |
Worked Example
A program is required to read the contents of a text file Data.txt into a 1D array DataArray. The file contains 25 integer values, one per line.
Write pseudocode to:
open the file for reading
read each value into the array
close the file
[4]
Answer
Correct use of
OPENFILE "Data.txt" FOR READ… [1 mark]Loop using
WHILE NOT EOF("Data.txt") DO … ENDWHILEorFOR 1 TO 25… [1 mark]Correct use of
READFILE "Data.txt", LineDatastoring into array with indexDataArray[Counter] ← LineData… [1 mark]Correct use of
CLOSEFILE "Data.txt"in an appropriate place … [1 mark]
Model answer:
DECLARE DataArray : ARRAY[1:25] OF STRING
DECLARE Counter : INTEGER
DECLARE LineData : STRING
Counter ← 1
OPENFILE "Data.txt" FOR READ
WHILE NOT EOF("Data.txt") DO
READFILE "Data.txt", LineData
DataArray[Counter] ← LineData
Counter ← Counter + 1
ENDWHILE
CLOSEFILE "Data.txt"Unlock more, it's free!
Was this revision note helpful?