File Operations CS Thinking Example 1

Follow the full solution, then compare it with the other examples linked below.

Example 1

easy
Write pseudocode to write three names to a file called 'names.txt', then read them back and display them.

Solution

  1. 1
    Step 1: Writing: OPEN 'names.txt' FOR WRITING. WRITE 'Alice'. WRITE 'Bob'. WRITE 'Charlie'. CLOSE file.
  2. 2
    Step 2: Reading: OPEN 'names.txt' FOR READING. WHILE NOT end of file: line = READ line. OUTPUT line. CLOSE file.
  3. 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