File access is normally handled by a set of procedures in a given language. These may differ in name, usage and complexity but they all share a common set of guidelines. This page will look at file access in pseudocode but you can also find a link to the Java mini-site and its coverage of file access.
The normal procedure to access a file is –
- open the file
- Access the file
- Close the file
Think of a file as a book. You can not read a book unless you open it and when you finish with the book you need to close it to protect the contents. The same goes for files. We can also open a file in different modes –
R – Read mode. Many programs can read from the same file
W – Write mode. Only ONE program can write to a file at a given time.
RW- Read-write mode. Only ONE program can write at once but it may also read from the file.
OPEN(Filename, accessMode) returns a file handle
This is a common way to open a file. The first parameter takes a file name while the second on will take the access mode. It will return a variable to allow access to the file. This is called the file handle and further access to the file will be made through this variable. It will return false or NULL if the file is already open in W or RW mode.
YOU CAN NOT READ FROM A FILE THAT IS BEING WRITTEN TO!
This is because what you read in may be changed as you read it. This will lead to some very strange inconsistencies. It is possible to alter a file once it has been opened in R mode. This can be handled by a notification system. (ever had a program prompt you to reload a file?)
The file name will be a string and will point to the name of the file. This can be relative or absolute (E.g. C:/files/myfile.txt or myfile.txt). Bare in mind your program will look for the files (if you use relative) in the same folder it was run from.
This method will close the file. If the file had already been closed it will cause an error. The file will perform a flush. This will write all data to the file and only close it once all data has been saved. Bare in mind that the hard drive works slower than the CPU so there could be a delay here. Files will use buffers to help make it more efficient so flushing the buffer on CLOSE is essential.