CIE IGCSE | 8.3.2.2 Write Items and Lines of Text to a File

Lesson objective

Open files in WRITE mode, write values in a planned order, close files after use, and explain replacement, file formats and copying between files.

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"
The agreed example format stores one task STRING per line
Saved lineText
1Revise arrays
2Check 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.

Assignments and file writes have different effects
Instruction completedTask variableDestination contents in our model
OPENFILE FOR WRITENot assignedEmpty replacement file
Task ← "Revise arrays"Revise arraysStill empty
First WRITEFILERevise arraysRevise arrays
Task ← "Check file handling"Check file handlingFirst line unchanged
Second WRITEFILECheck file handlingBoth new task lines
CLOSEFILECheck file handlingWriting 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.

      MATCH THE WRITING INSTRUCTION TO ITS ROLE

      Terminology

      Terminology

      WRITE mode

      Cambridge access creating a new file and losing existing data in that file.

      WRITEFILE

      Writes the current data supplied by its source variable into an opened file.

      Source variable

      The working variable whose current value is written.

      Destination file

      The file receiving the written data.

      Replacement save

      Writing a new sequence in place of previous file contents.

      Sequential writes

      Successive output items written in order during one open session.

      CLOSEFILE

      Ends the current access when the file is no longer needed.

      OUTPUT

      Displays information rather than writing it to a data file.

      File format

      The arrangement and interpretation agreed for the stored data.

      Line of text

      A character sequence stored as one line in the example format.

      Embedded line break

      A line separator within a STRING that may affect saved layout.

      Buffering

      Temporarily holding output before completing transfer through the storage system.

      File copy

      Reading source data and writing corresponding destination data.

      Append

      Adding to retained existing content; not the meaning of Cambridge WRITE mode.

      Known-count copy

      A copy relying on an explicitly specified number of source items.

      File identifier

      The filename given as a STRING literal or variable.

      Save confirmation

      A message reporting completion only after the intended operations succeed.

      Backup

      An additional recoverable copy protecting against loss.

      Questions

      Questions

      CHECK YOUR UNDERSTANDING

      Select all correct choices. Each exact set earns one point.

      1. What does Cambridge OPENFILE FOR WRITE mean?
      2. Task holds Revise arrays. What does WRITEFILE "Tasks.txt", Task do?
      3. Which actions alone write data to the file?
      4. How should a loop save three array elements in one sequence?
      5. A file is reopened FOR WRITE for each of Maya, Leo and Aisha, with one write per session. What remains after the final session?
      6. Which support a copy operation?
      7. Which statements about format are correct?
      8. Which are appropriate save practices?

      EXPLAIN AND COMPARE

      Write your answers before revealing each sample.

      1. Describe the sequence to save a STRING task to a text file.

      2. Explain why WRITE mode must be used carefully with an existing file.

      3. Compare OUTPUT Task and WRITEFILE "Tasks.txt", Task.

      4. Explain why a writing loop should open once outside the loop.

      5. Trace two writes using Task values Revise arrays then Check file handling.

      6. Describe how to copy one text line between different files.

      7. Explain why changing a source variable after a write does not change the saved item automatically.

      8. Suggest two checks before claiming a save is complete.

      BUILD IT | SAVE THREE REVISION TASKS

      Declare Tasks : ARRAY[1:3] OF STRING and assign “Revise arrays”, “Practise loops” and “Check file handling”. Write all three to Revision.txt, using one task per line in the agreed example format. Open once, write the array elements with a loop, close, then display a save confirmation. State what happens if Revision.txt already exists.

      Reveal one possible solution
      DECLARE Tasks : ARRAY[1:3] OF STRING
      DECLARE Position : INTEGER
      Tasks[1] ← "Revise arrays"
      Tasks[2] ← "Practise loops"
      Tasks[3] ← "Check file handling"
      OPENFILE "Revision.txt" FOR WRITE
      FOR Position ← 1 TO 3
        WRITEFILE "Revision.txt", Tasks[Position]
      NEXT Position
      CLOSEFILE "Revision.txt"
      OUTPUT "Revision tasks saved"

      The resulting file contains the three task lines in array order. Existing Revision.txt contents are replaced. The array remains unchanged. The confirmation assumes all operations succeeded; actual implementations should handle failures rather than announce success unconditionally.

      Flashcards

      Flashcards

      Click to flip. Select the ideas you need to revisit.

      0 cards selected for revision.

        Selections are kept while this page is open.

        Workbook

        Workbook

        COMING SOON

        The workbook for 8.3.2.2 Write Items and Lines of Text to a File is coming soon. Complete the matching task and written questions in your exercise book.