Page 159 - C-Language
P. 159
• "r": Open the file in read-only mode, with the cursor set to the beginning of the file.
• "r+": Open the file in read-write mode, with the cursor set to the beginning of the file.
• "w": Open or create the file in write-only mode, with its content truncated to 0 bytes. The
cursor is set to the beginning of the file.
• "w+": Open or create the file in read-write mode, with its content truncated to 0 bytes. The
cursor is set to the beginning of the file.
• "a": Open or create the file in write-only mode, with the cursor set to the end of the file.
• "a+": Open or create the file in read-write mode, with the read-cursor set to the beginning of
the file. The output, however, will always be appended to the end of the file.
Each of these file modes may have a b added after the initial letter (e.g. "rb" or "a+b" or "ab+"). The
b means that the file should be treated as a binary file instead of a text file on those systems where
there is a difference. It doesn't make a difference on Unix-like systems; it is important on Windows
systems. (Additionally, Windows fopen allows an explicit t instead of b to indicate 'text file' — and
numerous other platform-specific options.)
C11
• "wx": Create a text file in write-only mode. The file may not exist.
• "wbx": Create a binary file in write-only mode. The file may not exist.
The x, if present, must be the last character in the mode string.
Examples
Open and write to file
#include <stdio.h> /* for perror(), fopen(), fputs() and fclose() */
#include <stdlib.h> /* for the EXIT_* macros */
int main(int argc, char **argv)
{
int e = EXIT_SUCCESS;
/* Get path from argument to main else default to output.txt */
char *path = (argc > 1) ? argv[1] : "output.txt";
/* Open file for writing and obtain file pointer */
FILE *file = fopen(path, "w");
/* Print error message and exit if fopen() failed */
if (!file)
{
perror(path);
return EXIT_FAILURE;
}
/* Writes text to file. Unlike puts(), fputs() does not add a new-line. */
if (fputs("Output in file.\n", file) == EOF)
{
perror(path);
e = EXIT_FAILURE;
}
https://riptutorial.com/ 135

