| < Day Day Up > |
Random File Access
If you're adventurous, you can do random reads and
Opening Files for Read and Write
Until now, you've
Table 15.1. Summary of
|
|
open Command |
Reading? |
Writing? |
Append? |
Creates If Does Not Exist? |
Truncates Any Existing Data? |
|---|---|---|---|---|---|
|
open(F, "<file") or open(F, "file") |
Yes |
No |
No |
No |
No |
|
open(F, ">file") |
No |
Yes |
No |
Yes |
Yes |
|
open(F, ">>file") |
No |
Yes |
Yes |
Yes |
No |
|
open(F, "+<file") |
Yes |
Yes |
No |
No |
No |
|
open(F, "+>file") |
Yes |
Yes |
No |
Yes |
Yes |
|
open(F, "+>>file") |
Yes |
Yes |
Yes |
Yes |
No |
Notice the following:
Modes that specify "Append" can be tricky. On some systems such as Unix, data written to the file is always written at the end of the file, regardless of where the read pointer is. (You'll read more about that in a moment.)
You should almost never use +> . The contents of the file are erased as soon as it's opened.
When a file is opened, the operating system keeps track of where in the file you happen to be. This pointer is called the read pointer . For example, when a file is first opened for reading, the read pointer is at the beginning of the file, as shown here:
After you've read through the whole file, the read pointer is at the end of the file, as shown here:
To reposition the pointer to any spot within the file, you must use the seek function. The seek function takes two arguments: The first is an open filehandle, and the second is the offset in the file that you want to seek. The last argument is what the offset is relative to: 0, the beginning of the file; 1, the current position in the file; or 2, the end of the file. The following are some examples of seeking within a file:
# open existing file for reading and writing open(F, "+<file.txt") die "file.txt error: $!"; seek(F, 0, 2); # Seek to the end of the file print F "On the end"; # Appended to the end of the file seek(F, 0, 0); # Seek back to the beginning of the file print F "This is at the beginning";
The
tell
function returns the position of the current read pointer in a file. For example, after running the
By the Way
This section
| < Day Day Up > |