44 total
By the end of this subtopic, you should be able to:
File processing means working with files that are stored on secondary storage, such as a hard drive or SSD. A program may need to store data in a file so that the data is kept even after the program ends. It may also need to read data back later.
A file can store many pieces of related data. These are often stored as records. A record is a group of fields that belong together. For example, a student record might contain a name, address, and class name.
Example of a record structure:
TYPE StudentRecord
DECLARE name : STRING
DECLARE address : STRING
DECLARE className : STRING
ENDTYPE
In file processing, a program usually does four main jobs. It opens the file, reads from it or writes to it, and then closes it. Closing the file is important because it finishes the file operation properly and helps prevent data loss.
Before a program can use a file, it must open it. When a file is opened, the program chooses a mode. The mode tells the computer what the program wants to do with the file.
The three file modes you must know are:
After the program has finished with the file, it should close it. Closing a file ends access to the file and makes sure the data has been properly saved.
Basic pseudocode:
OPEN filename FOR READ
READ record FROM filename
CLOSE filename
OPEN filename FOR WRITE
WRITE record TO filename
CLOSE filename
OPEN filename FOR APPEND
WRITE record TO filename
CLOSE filename
Read mode is used when data already exists in the file and the program only needs to look at it or copy it into memory.
Write mode is used when the program wants to create new file contents. If the file already has data in it, that old data is overwritten. This means it is replaced.
Append mode is used when old data must be kept and new data should be added after it. This is useful for files such as logs, where each new event is added to the end.
Sign in to view full notes