number freopen(string path, string mode, number fd)
Parameters
path
[in] Path of new file
mode
[in] Type of access permitted
fd
[in] A valid file descriptor
Description:
The freopen function closes the file currently associated with fd and reassigns fd to the file specified by path.
freopen returns a file descriptor of the newly opened file. If an error occurs, the original file is closed and the function returns a negative value.
The new file associated with fd is opened with mode, which is a character string specifying 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 freopen 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 does not 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 does not exist.
"t"
Open in text (translated) mode; carriage return-linefeed (CR-LF) combinations are translated into single linefeed (LF) characters on input; LF characters are translated to CR-LF combinations on output. Also, CTRL+Z is interpreted as an end-of-file character on input. In files opened for reading or for writing and reading with "a+", the run-time library checks for a CTRL+Z at the end of the file and removes it, if possible. This is done because using fseek and ftell to move within a file may cause fseek to behave improperly near the end of the file. The t option is a Microsoft extension that should not be used where ANSI portability is desired.
"b"
Open in binary (untranslated) mode; the above translations are suppressed.
Return value:
freopen returns a file descriptor of the newly opened file. If an error occurs, the original file is closed and the function returns a negative value.
Example
import standard.C.io
define FILENAME "test.txt"
class Main {
function Main() {
var fd;
var ch;
var i;
var buffer = "Test of fputc\n";
// Open file for write
if (fd = fopen(FILENAME, "w")) {
// Print line to stream using fputc
ch = buffer[0];
i = 0;
while (ch) {
fputc(ch, fd);
i++;
ch = buffer[i];
}
freopen(FILENAME, "r", fd);
buffer = "";
fread(buffer, 1, 15, fd);
echo "$buffer\n";
fclose(fd);
} else
echo "Problem opening the file\n";
}
}
Results
Testing fputs.