File Operations CS Thinking Example 3
Follow the full solution, then compare it with the other examples linked below.
Example 3
mediumWrite pseudocode that reads a file of numbers (one per line), calculates their total, and writes the result to a new file 'total.txt'.
Solution
- 1 Step 1: OPEN 'numbers.txt' FOR READING. SET total = 0. WHILE NOT end of file: num = INT(READ line). total = total + num. CLOSE file.
- 2 Step 2: OPEN 'total.txt' FOR WRITING. WRITE STRING(total). CLOSE file.
Answer
Read numbers in a loop, accumulate total, write result to new file. Remember to convert string to integer when reading.
Combining file reading with data processing is a common pattern. The data read from a file is typically a string and must be converted to the appropriate type for calculations.
About File Operations
The operations of reading data from files and writing data to files on a storage device, allowing programs to persist information beyond a single run. The standard pattern is: open the file, read from or write to it, then close the file to ensure data is saved properly.
Learn more about File Operations โMore File Operations Examples
Example 1 easy
Write pseudocode to write three names to a file called 'names.txt', then read them back and display
Example 2 mediumExplain the difference between opening a file in WRITE mode vs APPEND mode. When would you use each?
Example 4 hardA program reads a CSV file where each line has 'name,score' (e.g., 'Alice,85'). Write pseudocode to