Open a file
File_Type fopen (String_Type f, String_Type m)
The fopen
function opens a file f
according to the mode
string m
. Allowed values for m
are:
"r" Read only
"w" Write only
"a" Append
"r+" Reading and writing at the beginning of the file.
"w+" Reading and writing. The file is created if it does not
exist; otherwise, it is truncated.
"a+" Reading and writing at the end of the file. The file is created
if it does not already exist.
<tscreen><verb>
In addition, the mode string can also include the letter \var{'b'}
as the last character to indicate that the file is to be opened in
binary mode.
Upon success, \var{fopen} a \var{File_Type} object which is meant to
be used in other operations that require an open file. Upon
failure, the function returns \var{NULL}.
\example
The following function opens a file in append mode and writes a
string to it:
<tscreen><verb>
define append_string_to_file (file, str)
{
variable fp = fopen (file, "a");
if (fp == NULL) verror ("%s could not be opened", file);
() = fputs (string, fp);
() = fclose (fp);
}
Note that the return values from fputs
and fclose
are
ignored.
There is no need to explicitly close a file opened with fopen
.
If the returned File_Type
object goes out of scope, S-lang
will automatically close the file. However, explicitly closing a
file after use is recommended.
fclose, fgets, fputs