Published by Patrick Mutisya · 14 days ago
Write pseudocode to handle text files that consist of one or more lines.
| Operation | Pseudocode Syntax | Description |
|---|---|---|
| Open file for reading | OPEN fileName FOR READ AS file | Creates a file handle for sequential reading. |
| Open file for writing | OPEN fileName FOR WRITE AS file | Creates a new file (or overwrites existing) for sequential writing. |
| Open file for appending | OPEN fileName FOR APPEND AS file | Opens an existing file and positions the pointer at the end. |
| Read a line | READLINE file INTO line | Reads the next line of text; returns EOF when no more lines. |
| Write a line | WRITELINE file, line | Writes the string line followed by a newline character. |
| Close file | CLOSE file | Releases the file handle and flushes buffers. |
Example:
OPEN "data.txt" FOR READ AS f
WHILE NOT EOF(f) DO
READLINE f INTO currentLine
// Process currentLine, e.g., count words
END WHILE
CLOSE f
Example:
OPEN "output.txt" FOR WRITE AS f
FOR i FROM 1 TO n DO
line ← "Record " & i
WRITELINE f, line
END FOR
CLOSE f
This pattern is useful for log files.
OPEN "log.txt" FOR APPEND AS f
WRITELINE f, "Program started at " & CURRENTTIME()
CLOSE f
When the number of lines is not known in advance, the EOF test controls the loop.
The total number of lines read can be stored in a variable lineCount:
lineCount ← 0
OPEN "input.txt" FOR READ AS f
WHILE NOT EOF(f) DO
READLINE f INTO line
lineCount ← lineCount + 1
// Additional processing here
END WHILE
CLOSE f
/* lineCount now holds the number of lines in the file */
Mathematically, if \$L\$ is the number of lines, then after the loop \$lineCount = L\$.
sum ← 0
count ← 0
OPEN "numbers.txt" FOR READ AS f
WHILE NOT EOF(f) DO
READLINE f INTO line
value ← STRINGTOINT(line)
sum ← sum + value
count ← count + 1
END WHILE
CLOSE f
IF count > 0 THEN
average ← sum / count
ELSE
average ← 0
END IF
/* sum and average now contain the results */