10.3.1 Creating and Appending Text Files
Variables and arrays hold data while a program is running. A text file allows selected information to remain available after the program finishes. This section develops the pseudocode needed to create a fresh text file and to add new lines to an existing file.
By the end of this section, you should be able to:
- Explain why a program may need persistent storage.
- Describe a text file as a sequence of character-based lines.
- Distinguish between
WRITEandAPPENDmode. - Use
OPENFILE,WRITEFILEandCLOSEFILEcorrectly. - Write one or several lines to a text file.
- Select a suitable file mode for a given problem.
Why Programs Need Files
Data stored in ordinary variables or arrays is normally available only while the program is executing. When the program ends, that working data is no longer available unless it has been saved somewhere persistent.
Consider a makerspace program that records equipment inspections. The inspection result must still exist tomorrow, after the computer has been restarted. A text file can preserve each completed inspection as a line.
| Storage location | Typical lifetime | Example |
|---|---|---|
| Variable or array | Usually only during the current program run | The inspection note currently being entered |
| File | Remains available after the program closes | A saved history of completed inspections |
What Is Stored in a Text File?
A text file stores characters arranged into lines. Each call to WRITEFILE
writes one string as one line of the file.
Laser cutter | passed
Soldering station | cable replaced
3D printer | nozzle cleaned
| Feature | Meaning |
|---|---|
| Filename | Identifies the file, for example "InspectionLog.txt". |
| Line | One sequence of characters stored between line boundaries. |
| Text value | The STRING written by a WRITEFILE statement. |
Choosing Between WRITE and APPEND
The mode supplied to OPENFILE determines what should happen to the file's
existing contents.
| Mode | Use it when... | Effect on existing content |
|---|---|---|
WRITE |
The program must create a fresh version of the file. | Previous contents are replaced. |
APPEND |
The program must preserve earlier lines and add new data at the end. | Previous contents remain. |
WRITE mode
can remove its earlier contents. Choose the mode before opening the file.
Creating a Fresh Text File with WRITE
A program that produces a new daily summary should start with a clean file. The file is
opened in WRITE mode, one or more lines are written, and the file is closed.
DECLARE SummaryLine : STRING
SummaryLine ← "Workshop checks completed: 14"
OPENFILE "DailySummary.txt" FOR WRITE
WRITEFILE "DailySummary.txt", SummaryLine
CLOSEFILE "DailySummary.txt"
Resulting file
Workshop checks completed: 14
WRITE when the new output is intended to replace the previous version,
such as a report that is regenerated from current data.
Adding a New Line with APPEND
A historical log should normally preserve its earlier entries. Opening the file in
APPEND mode places newly written lines after the existing content.
File before the program runs
Laser cutter | passed
Soldering station | cable replaced
Pseudocode
DECLARE NewEntry : STRING
NewEntry ← "3D printer | nozzle cleaned"
OPENFILE "InspectionLog.txt" FOR APPEND
WRITEFILE "InspectionLog.txt", NewEntry
CLOSEFILE "InspectionLog.txt"
File after the program runs
Laser cutter | passed
Soldering station | cable replaced
3D printer | nozzle cleaned
The Required Sequence: Open, Write, Close
File operations should follow a clear sequence. The file must be opened in the required mode before data are written, and it should be closed after the final write.
| Stage | Example statement | Purpose |
|---|---|---|
| 1. Open | OPENFILE "InspectionLog.txt" FOR APPEND |
Makes the file available in the selected mode. |
| 2. Write | WRITEFILE "InspectionLog.txt", NewEntry |
Sends one line of text to the open file. |
| 3. Close | CLOSEFILE "InspectionLog.txt" |
Finishes access to the file and releases it. |
Writing Several Lines
Once a file is open, several WRITEFILE statements may be used before it is
closed. Each statement writes one line.
OPENFILE "ShiftReport.txt" FOR WRITE
WRITEFILE "ShiftReport.txt", "Morning workshop report"
WRITEFILE "ShiftReport.txt", "Safety checks: complete"
WRITEFILE "ShiftReport.txt", "Machines unavailable: 2"
CLOSEFILE "ShiftReport.txt"
Writing an array to a text file
A loop can write one array element per line. The array itself is still temporary; the resulting file is persistent.
DECLARE MachineName : ARRAY[1:4] OF STRING
DECLARE Index : INTEGER
OPENFILE "MachineList.txt" FOR WRITE
FOR Index ← 1 TO 4
WRITEFILE "MachineList.txt", MachineName[Index]
NEXT Index
CLOSEFILE "MachineList.txt"
WRITE mode inside the loop could repeatedly replace the
file, leaving only the final line.
Choosing the Correct Mode
| Requirement | Mode | Reason |
|---|---|---|
| Regenerate today's room-status report | WRITE |
The new report should replace yesterday's version. |
| Add a new fault to a maintenance history | APPEND |
Earlier faults must remain in the file. |
| Export the current contents of an array | WRITE |
The file should represent the array's current state. |
| Add today's attendance note to a year-long log | APPEND |
The file is a growing sequence of entries. |
Interactive: Text File Mode Simulator
Select WRITE or APPEND, enter a new line, and step through
opening, writing and closing the file. The preview shows exactly when previous content
is replaced or preserved.
Common Mistakes and Misconceptions
- Using
WRITEwhen earlier file contents must be preserved. - Assuming
APPENDinserts data at the beginning of the file. - Calling
WRITEFILEbeforeOPENFILE. - Forgetting to close the file after writing.
- Using inconsistent filenames across the open, write and close statements.
- Opening a file in
WRITEmode repeatedly inside a loop. - Assuming that a text file automatically stores numbers as numeric data types.
- Using
READorEOFlogic on this page; those belong in 10.3.2.
Practice
Task 1: Select the mode
Choose WRITE or APPEND and justify each decision.
- Create a fresh weekly stock summary.
- Add a new temperature alert to an existing history.
- Replace an old list of active users with the current list.
- Add one new delivery event to a tracking log.
Task 2: Complete the pseudocode
Write pseudocode that adds the string stored in NewMessage to the end of
"SystemEvents.txt".
- Open the file in the correct mode.
- Write the value of
NewMessage. - Close the file.
Task 3: Write several lines
VisitorName is an array declared from index 5 to index 12.
- Write pseudocode to create
"Visitors.txt". - Use a loop to write one visitor name per line.
- Explain why the file should be opened before the loop.
Task 4: Diagnose the error
FOR Index ← 1 TO 6
OPENFILE "Results.txt" FOR WRITE
WRITEFILE "Results.txt", Result[Index]
CLOSEFILE "Results.txt"
NEXT Index
- Predict what is likely to remain in the file.
- Rewrite the pseudocode so that all six lines are stored.
Review
| Question | Strong answer should include |
|---|---|
| Why is a file needed? | To keep data available after the program finishes. |
What does WRITE mode do? |
Starts a fresh file or replaces the previous contents. |
What does APPEND mode do? |
Preserves existing lines and adds new lines at the end. |
| What is the correct operation sequence? | Open the file, write the required line or lines, then close it. |
| How is an array saved one item per line? | Open once, use a loop containing WRITEFILE, then close once. |
| What is covered next? | Opening a file for reading, processing several lines and testing for EOF. |