The fopen function opens the file specified by filename.
The function returns a number representing the file descriptor for the open file. A null value indicates an error.
The character string mode specifies the type of access requested for the file, as follows:
"r"
Opens for reading. If the file does not exist or cannot be found, the fopen call fails.
"w"
Opens an empty file for writing. If the given file exists, its contents are destroyed.
"a"
Opens for writing at the end of the file (appending) without removing the EOF marker before writing new data to the file; creates the file first if it doesn't exist.
"r+"
Opens for both reading and writing. (The file must exist.)
"w+"
Opens an empty file for both reading and writing. If the given file exists, its contents are destroyed.
"a+"
Opens for reading and appending; the appending operation includes the removal of the EOF marker before new data is written to the file and the EOF marker is restored after writing is complete; creates the file first if it doesn't exist.
In addition to the above values, the following characters can be included in mode to specify the translation mode for newline characters: b
Open in binary (untranslated) mode; translations involving carriage-return and linefeed characters are suppressed.
S
Specifies that caching is optimized for, but not restricted to, sequential access from disk.
R
Specifies that caching is optimized for, but not restricted to, random access from disk.
T
Specifies a file as temporary. If possible, it is not flushed to disk.
D
Specifies a file as temporary. It is deleted when the last file pointer is closed.
Return value:
The function returns a number used to identify the file descriptor for the open file.
Example
import standard.C.io
class Main {
function Main() {
// Open for read (will fail if file "test1.txt" does not exist)
if(!(var fd1 = fopen( "test1.txt", "r" )))
echo "The file 'test1.txt' was not opened\n";
else {
echo "The file 'test1.txt' was opened\n";
// Close the file
if(fclose(fd1) != 0)
echo "The file 'test1.txt' was not closed\n";
}
// Open for write
if(!(var fd2 = fopen( "test2.txt", "w+" )))
echo "The file 'test2.txt' was not opened\n";
else {
echo "The file 'test2.txt' was opened\n";
// Close the file
if(fclose(fd2) != 0)
echo "The file 'test2.txt' was not closed\n";
}
}
}
Results
The file 'test1.txt' was not opened
The file 'test2.txt' was opened