Back

Typical operations on files

Introduction
When you write programs, you will at some point need to save data to a file or get back data you have already saved. How you do this will depend on the language you are using but the following notes using pseudo-code are common to most languages.

Opening, reading and writing files
The usual method for this is to:

    • DECLARE a variable.
    • ASSIGN the file that you want to work with to that variable.
    • OPEN the file
    • READ the file one line at a time.
    • WRITE to the file, one line at a time.
    • CLOSE the files when finished.

Updating a file / appending data (append means 'add on to the end').
If you wanted to update a file:

    1. You would need to get the original file, using DECLARE, ASSIGN, OPEN and READ or WRITE as described above.
    2. You then need to create a second file, using DECLARE, ASSIGN, OPEN and READ or WRITE as described above.
    3. You would copy across the original data plus the extra data into this second file.
    4. The first, original file would then be renamed as a backup file.
    5. The second updated file would be given the name of the original file.
    6. Close the files.

Inserting / deleting / appending an item in a file
Inserting and deleting data in a file requires two files and is similar to updating a file:

    1. You would need to get the original file, using DECLARE, ASSIGN, OPEN and READ or WRITE as described above.
    2. You then need to create a second file, using DECLARE, ASSIGN, OPEN and READ or WRITE as described above.
    3. You would copy across the original data to the second file, up to the point you want to add or delete some data.
    4. You then add or delete the data you want to add or delete.
    5. You then copy the remaining part of the file from the first file across to the second file.
    6. The first, original file would then be renamed as a backup file.
    7. The second updated file would be given the name of the original file.
    8. Close the files.

Back