|
To open a file to write or to read data, a "File Handle" is given usually in capital letters, then
provide the appropriate "access mode" options like read, read/write, write options and then the filename of the file.
Example:
#! C:\programfiles\perl\bin\perl
print "content-type: text/html\n\n";
open(HANDLE,"<file1.txt")or die "can't open file: $!";
while ($record = <HANDLE>)
{
print $record;
}
close (HANDLE);
Result:
qddddddd
In the above example name of the file handle is "HANDLE", we open a file "file1.txt" with read only acess
mode, if an error occurs the "die" statement displays a error message. When the file is open all contents of the file
is displayed using a while loop.
The user can also use sysopen() instead of open(). If the mode is missing by default the file takes the
default mode that is "<" (read only) mode.Using the file handles the user can add any data like array values, hash values,
variable's, text etc.
The following is the table of modes that can be used for file handling.
| MODE |
DESCRIPTION |
| < |
READ |
| > |
WRITE, CREATE, TRUNCATE |
| >> |
WRITE, APPEND, CREATE |
| +< |
READ, WRITE |
| +> |
READ, WRITE, TRUNCATE, CREATE |
| +>> |
READ, WRITE, CREATE, APPEND |
The following table list the flags that can be used with the sysopen() function
| VALUE |
DESCRIPTION |
| O_RDWR |
Read and Write |
| O_RDONLY |
Read Only |
| O_WRONLY |
Write Only |
| O_CREAT |
Create the file |
| O_APPEND |
Append the file |
| O_TRUNC |
Truncate the file |
| O_EXCL |
Stops if file already exists |
| O_NONBLOCK |
Non-Blocking usability |
Example:
#! C:\programfiles\perl\bin\perl
print "content-type: text/html\n\n";
sysopen(HANDLE,'file1.txt',O_RDONLY)or die "can't open file: $!";
while ($record = <HANDLE>)
{
print $record;
}
close(HANDLE);
Result:
Hscriptssssssssssss
In the above example we have used sysopen(), with the flag "O_RDONLY" which opens file in the
read only mode.In the while loop we print the conetents of the file.
|