11.4 Text File Handling EMK Notes 2024
11.4 Text File Handling EMK Notes 2024
➢ Once file is opened in WRITE or APPEND mode, it can be written to a line at a time:
WRITEFILE < file identifier >, <variable>
Note: In both cases, variable must be of data type STRING.
➢ EOF Function is used to test for end of a file. It returns a value TRUE if end of a file
has been reached and FALSE otherwise.
EOF (<File Identifier>)
➢ When a file is no longer being used it should be closed:
CLOSEFILE <file identifier>
Writing Text Into File:
pseudocode statements provide facilities for writing to a file:
Following
OPENFILE <filename> FOR WRITE // open the file for writing
WRITEFILE <filename >, <stringValue> // write a line of text to the file
CLOSEFILE <filename > // close file
OUTPUT textLine
UNTILL EOF( myFile) paperscambridge.com
CLOSEFILE (myFile)
Exam Style Question
ESQ 1: Algorithm will process data from a test taken by a group of students. Algorithm
will prompt and input name and test mark for 35 students. Algorithm will add names
of all students with test mark of less than 20 to existing text file Support_List.txt which
already contains data from other group tests. 9618 P22 Oct 22
(i) Describe steps that algorithm should perform. Do not include pseudocode in your
answer. [5]
Ans: 1. Open file in APPEND mode
2. Prompt and Input a student name and mark
3. If mark greater than or equal to 20 jump to step 5
4. Write only the name to the file
5. Repeat from Step 2 for 35 times.
(ii) Explain why it is better to store names of students in a file rather than in array.
Ans: Data in a file is saved after computer is switched off and stored permanently. No
need to re-enter data when program is re-run.
(iii) Explain why WRITE mode cannot be used in the answer to part (a)(i)
Ans: So that existing file data is not overwritten.
ESQ # 2: LogArray is 1D array containing 500 elements of type STRING. A procedure,
LogEvents, is required to add data from array to end of existing file LoginFile.txt
Unused array elements are assigned value "Empty". These can occur anywhere in array
and should not added to file. Write pseudocode for procedure LogEvents. 9618-SP-21
Solution:
PROCEDURE LogEvents ( )
DECLARE FileData : STRING
DECLARE ArrayIndex : INTEGER
OPENFILE "LoginFile.txt" FOR APPEND
FOR ArrayIndex ← 1 TO 500 // 0 TO 499
IF LogArray[ArrayIndex] < > "Empty"
THEN
FileData ← LogArray[ArrayIndex]
WRITEFILE "LoginFile.txt", FileData
ENDIF
NEXT
CLOSEFILE "LoginFile.txt"
ENDPROCEDURE
ESQ# 3 : A procedure Preview( ) will: 9618 P21 May 21
take name of a text file as a parameter
output a warning message if file is empty
otherwise output first five lines from file (or as many lines as there are in file
if this number is less than five).
Write pseudocode for the procedure Preview()
Ans:
paperscambridge.com
**************