next up previous contents
Next: Binary Files Up: File Functions Previous: Reading Directories

Reading and Writing Files

We have just introduced the concept of a Directory Handle for referring to a Directory on disk.

We now introduce a similar concept of File Handle for referring to a File on disk from which we can read data and to which we can write data.

Similar ideas of opening and closing the files exist.

You use the open() operator to open a file (for reading):

     open(FILEHANDLE,"file_on_device");

To open a file for writing you must use the ``>'' symbol in the open() operator:

     open(FILEHANDLE,">outfile");

Write always starts writing to file at the start of the file. If the file already exists and contains data. The file will be opened and the data overwritten.

To open a file for appending you must use the ``>>'' symbol in the open() operator:

     open(FILEHANDLE,">>appendfile");

The close() operator closes a file handle:

     close(FILEHANDLE);

To read from a file you simply use the <FILEHANDLE> command which reads one line at a time from a FILEHANDLE and stores it in a special Perl variable $_.

For example, read.pl:

open(FILE,"myfile") 
   || die "cannot open file";
while(<FILE>)
{ print $_; # echo line read
}
close(FILE);

To write to a file you use the Print command and simply refer to the FILEHANDLE before you format the output string via:

    print FILEHANDLE "Output String\n";

Therefore to read from one file infile and copy line by line to another outfile we could do readwrite.pl:

open(IN,"infile") 
   || die "cannot open input file";
open(OUT,"outfile") 
   || die "cannot open output file";
while(<IN>)
{ print OUT $_; # echo line read
}
close(IN);
close(OUT);


next up previous contents
Next: Binary Files Up: File Functions Previous: Reading Directories
dave@cs.cf.ac.uk