File Operations CS Thinking Example 1
Follow the full solution, then compare it with the other examples linked below.
Example 1
easyWrite pseudocode to write three names to a file called 'names.txt', then read them back and display them.
Solution
- 1 Step 1: Writing: OPEN 'names.txt' FOR WRITING. WRITE 'Alice'. WRITE 'Bob'. WRITE 'Charlie'. CLOSE file.
- 2 Step 2: Reading: OPEN 'names.txt' FOR READING. WHILE NOT end of file: line = READ line. OUTPUT line. CLOSE file.
- 3 Step 3: Key pattern: always open โ use โ close. Opening for writing creates or overwrites the file. Opening for reading requires the file to exist.
Answer
Write: open, write lines, close. Read: open, read lines in a loop until end of file, close.
File operations allow programs to persist data between runs. The open-use-close pattern ensures resources are properly managed and data is not corrupted.
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 2 medium
Explain the difference between opening a file in WRITE mode vs APPEND mode. When would you use each?
Example 3 mediumWrite pseudocode that reads a file of numbers (one per line), calculates their total, and writes the
Example 4 hardA program reads a CSV file where each line has 'name,score' (e.g., 'Alice,85'). Write pseudocode to