Learn
8.3.2.2 | WRITE ITEMS AND LINES OF TEXT TO A FILE
01 | A VALUE ON SCREEN IS NOT A SAVED FILE
A task-list program receives “Revise arrays” from the user. It can store the task in a STRING and show it on screen, but those actions alone do not preserve it for a later run.
Writing transfers data from the running program into a file. A text file stores data represented as characters. The program must explicitly open the destination for writing, write the required items and close the access when finished.
In this lesson our simple file format uses one STRING item on each line. This makes the saved order easy to inspect and matches the line-of-text examples used in the reading lesson.
02 | OPENFILE FOR WRITE PREPARES THE DESTINATION
OPENFILE identifies the file and its mode. FOR WRITE prepares a new output file. Cambridge specifies that a new file is created and any existing data in that file is lost.
This means opening Tasks.txt FOR WRITE is not an instruction to preserve its old tasks and add another. It starts a replacement file for this writing session.
Opening alone does not write the new task value. That needs WRITEFILE. Read the filename carefully before choosing WRITE mode.
OPENFILE "Tasks.txt" FOR WRITE
03 | WRITEFILE TAKES A VALUE FROM A VARIABLE
WRITEFILE uses the file identifier followed by a source variable, separated by a comma. The variable’s current data is written into the opened file.
Task holds “Revise arrays”. The instruction writes that value, not the identifier word Task. The variable still holds the same STRING afterwards: writing does not remove it from working memory.
WRITEFILE does not display a message on screen. OUTPUT is a separate instruction with a different destination.
DECLARE Task : STRING Task ← "Revise arrays" OPENFILE "Tasks.txt" FOR WRITE WRITEFILE "Tasks.txt", Task CLOSEFILE "Tasks.txt"
04 | ADD SUCCESSIVE ITEMS DURING ONE OPEN SESSION
With the file opened once, successive WRITEFILE instructions write successive items. For our one-item-per-line text format, the resulting file contains the two task lines in the order written.
Changing Task between writes supplies a different value for the second item. The first written line does not automatically change when Task changes.
The important distinction is between another write in the current session and reopening the file FOR WRITE. The former continues writing; the latter replaces existing contents again.
DECLARE Task : STRING OPENFILE "Tasks.txt" FOR WRITE Task ← "Revise arrays" WRITEFILE "Tasks.txt", Task Task ← "Check file handling" WRITEFILE "Tasks.txt", Task CLOSEFILE "Tasks.txt"
| Saved line | Text |
|---|---|
| 1 | Revise arrays |
| 2 | Check file handling |
05 | CLOSE AFTER THE WRITES ARE FINISHED
CLOSEFILE ends the file access when the writing task is complete. Proper closing releases the resources associated with that open file.
Real environments may buffer writes: temporarily hold output before completing transfer to storage. Closing normally completes pending output through the environment’s file mechanisms. Exact durability guarantees depend on the system; closing is not a promise against every possible storage failure.
Do not treat closing as deleting the file or clearing its source variables. Nor should a program report a successful save if an operation failed. The simple examples here assume the destination is accessible and all operations succeed.
CLOSEFILE "Tasks.txt" OUTPUT "Tasks saved"
06 | TRACE THE FILE AS IT IS BUILT
Assume Tasks.txt previously contained “Old task”. Opening it FOR WRITE loses that old content before the new tasks are written.
The trace below separates variable assignments from file writes. Assigning a new Task changes working state only; WRITEFILE records the current value in the output sequence.
| Instruction completed | Task variable | Destination contents in our model |
|---|---|---|
| OPENFILE FOR WRITE | Not assigned | Empty replacement file |
| Task ← "Revise arrays" | Revise arrays | Still empty |
| First WRITEFILE | Revise arrays | Revise arrays |
| Task ← "Check file handling" | Check file handling | First line unchanged |
| Second WRITEFILE | Check file handling | Both new task lines |
| CLOSEFILE | Check file handling | Writing session complete |
07 | STEP THROUGH THE WRITING SESSION
The simulation begins with an existing file containing one old line. Follow the open, assignments, writes and close, and notice exactly when the simulated destination changes.
SIMULATED Tasks.txt CONTENTS
This is a logical illustration of the file contents produced by successful operations. It does not create a file on your device or model operating-system buffering. Closing marks the writing session complete.
08 | SAVE EVERY ELEMENT OF AN ARRAY
A loop can write one array element per iteration. StudentNames contains three already-assigned STRING values: Maya, Leo and Aisha.
OPENFILE is before the loop and CLOSEFILE after it. Position selects each source element, so the same WRITEFILE instruction saves all three in order.
The loop reads working array values and writes the file. It does not change the array elements. Its bounds match the declared array.
DECLARE StudentNames : ARRAY[1:3] OF STRING DECLARE Position : INTEGER StudentNames[1] ← "Maya" StudentNames[2] ← "Leo" StudentNames[3] ← "Aisha" OPENFILE "Students.txt" FOR WRITE FOR Position ← 1 TO 3 WRITEFILE "Students.txt", StudentNames[Position] NEXT Position CLOSEFILE "Students.txt"
09 | DO NOT REOPEN FOR WRITE INSIDE THE LOOP
If a program opens Students.txt FOR WRITE on each iteration, each open replaces the previous saved contents. Writing one name and closing each time leaves only the final name after the last iteration.
To save the collection in one output sequence, open once, perform all writes, then close once. Repeating WRITEFILE is useful; repeating replacement access is a different operation.
A language may provide an append mode for adding to an existing file, but this Cambridge syllabus’s listed modes are READ and WRITE. Do not assume FOR WRITE means append.
10 | WRITE ORDER MUST MATCH THE READING FORMAT
If the reader expects three names, one per line, the writer must produce those names in that arrangement. A title line such as “Student list” would be extra data unless the reading design accounts for it.
Keep the format agreed between writing and reading. File data has structure even when it is easy for a person to read.
A source STRING containing line breaks may produce more than one text line in a real environment. Our introductory examples use strings without embedded line breaks, so each item corresponds to one line. Consult the language’s file-writing API when implementing actual line separators.
11 | COPY TEXT FROM ONE FILE INTO ANOTHER
Copying uses READ access for the source and WRITE access for the destination. READFILE assigns a source line to LineOfText; WRITEFILE uses that current value to create the corresponding destination item.
The example assumes Source.txt exists and contains at least one line. It copies one line only, not an arbitrary whole file. The source and destination are deliberately different filenames.
Opening an existing destination FOR WRITE replaces its contents. Never use the source file itself as the replacement destination before its data has been safely retained.
DECLARE LineOfText : STRING OPENFILE "Source.txt" FOR READ OPENFILE "Copy.txt" FOR WRITE READFILE "Source.txt", LineOfText WRITEFILE "Copy.txt", LineOfText CLOSEFILE "Source.txt" CLOSEFILE "Copy.txt"
12 | COPY A KNOWN NUMBER OF LINES
If Source.txt is known to contain exactly three lines, a loop can repeat the read-then-write pair three times. Each iteration transfers the next source value.
LineOfText is reused, but each write captures its current value before the next read replaces it. The source contents remain unchanged by this reading task.
The fixed count is an explicit assumption. An unknown-length file requires the environment’s suitable end-of-file strategy rather than guessing how many reads will succeed.
DECLARE LineOfText : STRING DECLARE LineNumber : INTEGER OPENFILE "Source.txt" FOR READ OPENFILE "Copy.txt" FOR WRITE FOR LineNumber ← 1 TO 3 READFILE "Source.txt", LineOfText WRITEFILE "Copy.txt", LineOfText NEXT LineNumber CLOSEFILE "Source.txt" CLOSEFILE "Copy.txt"
13 | FILENAMES CAN BE STRING VARIABLES
A STRING variable can hold the output filename. This lets the same sequence use a filename chosen earlier in the program.
Use OutputFile without quotes to refer to its stored filename. "OutputFile" would instead be literal filename text. Task is also unquoted because its value is the source data.
A name or path must identify a permitted destination. Checking that the filename is a STRING is not enough to guarantee that writing is possible.
DECLARE OutputFile : STRING DECLARE Task : STRING OutputFile ← "Tasks.txt" Task ← "Revise arrays" OPENFILE OutputFile FOR WRITE WRITEFILE OutputFile, Task CLOSEFILE OutputFile
14 | CHECK THE WHOLE SAVE TASK
Assign every source value before writing it. Open in the correct mode before WRITEFILE. Keep the file open across the intended sequence, then close when finished.
For a replacement save, make sure all required current data is included. Writing only the newly added task after opening FOR WRITE would lose the earlier tasks rather than preserve the complete list.
Real programs need appropriate handling for inaccessible locations, permission failures, insufficient storage and interrupted writes. Backups or safer replacement strategies may be appropriate for important records; a basic WRITE example is not a full data-protection design.
15 | EXPLAIN THE SOURCE AND DESTINATION
A useful explanation is: “WRITEFILE reads Task’s current value and writes it to Tasks.txt. The variable remains unchanged. The file was opened once FOR WRITE, so the new sequence replaces its previous contents.”
Keep OUTPUT, assignment and WRITEFILE distinct. OUTPUT displays, assignment changes working data, and WRITEFILE writes saved data. Reopening FOR WRITE starts replacement again; successive writes within one open session build the output sequence.
You have now completed the Topic 8 learning pages. Use the revision and end-of-topic review to connect programming concepts, arrays and file handling.