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:
- You would need to get the original file, using DECLARE, ASSIGN, OPEN and READ or WRITE as described above.
- You then need to create a second file, using DECLARE, ASSIGN, OPEN and READ or WRITE as described above.
- You would copy across the original data plus the extra data into this second file.
- The first, original file would then be renamed as a backup file.
- The second updated file would be given the name of the original file.
- 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:
- You would need to get the original file, using DECLARE, ASSIGN, OPEN and READ or WRITE as described above.
- You then need to create a second file, using DECLARE, ASSIGN, OPEN and READ or WRITE as described above.
- You would copy across the original data to the second file, up to the point you want to add or delete some data.
- You then add or delete the data you want to add or delete.
- You then copy the remaining part of the file from the first file across to the second file.
- The first, original file would then be renamed as a backup file.
- The second updated file would be given the name of the original file.
- Close the files.