man pages section 3: Basic Library Functions
The fopen() function opens the file whose pathname is the string pointed to by filename, and associates a stream with it.
The argument mode points to a string beginning with one of the following sequences:
Open file for reading
Truncate to zero length or create file for writing
Append; open or create file for writing at end-of-file
Open file for update (reading and writing)
Truncate to zero length or create file for update
Append; open or create file for update, writing at end-of-file
The character b has no effect, but is allowed for ISO C standard conformance (see standards(7)). Opening a file with read mode (r as the first character in the mode argument) fails if the file does not exist or cannot be read.
Opening a file with exclusive mode (x somewhere after the initial w or a in the mode argument) fails if the file already exists or cannot be created.
Opening a file with append mode (a as the first character in the mode argument) causes all subsequent writes to the file to be forced to the then current end-of-file, regardless of intervening calls to fseek(3C). If two separate processes open the same file for append, each process may write freely to the file without fear of destroying output being written by the other. The output from the two processes will be intermixed in the file in the order in which it is written.
When a file is opened with update mode (+ as the second or third character in the mode argument), both input and output may be performed on the associated stream. However, output must not be directly followed by input without an intervening call to fflush(3C) or to a file positioning function (fseek(3C), fsetpos(3C), or rewind(3C)), and input must not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file.
When opened, a stream is fully buffered if and only if it can be determined not to refer to an interactive device. The error and end-of-file indicators for the stream are cleared.
If mode begins with w or a and the file did not previously exist, upon successful completion, fopen() function will mark for update the st_atime, st_ctime and st_mtime fields of the file and the st_ctime and st_mtime fields of the parent directory.
If mode begins with w and the file did previously exist, upon successful completion, fopen() will mark for update the st_ctime and st_mtime fields of the file. The fopen() function will allocate a file descriptor as open(2) does.
The largest value that can be represented correctly in an object of type off_t will be established as the offset maximum in the open file description.
Additional mode characters are supported in this implementation. These additional characters must appear after r, w, or a.
Specifying e in the mode argument indicates the file is being opened with the O_CLOEXEC flag. This sets the FD_CLOEXEC for the underlying file descriptor. For more information, see the open(2) man page.
Specifying f in the mode argument indicates the file is being opened with the O_CLOFORK flag. This sets the FD_CLOFORK for the underlying file descriptor. For more information, see the open(2) man page.
Specifying x in the mode argument indicates the file is being opened in exclusive mode; the file is opened with the O_EXCL flag. For more information, see the open(2) man page.
The fopen_s() function is part of the bounds checking interfaces specified in the C11 standard, Annex K. It is similar to the fopen() function, except for a different return type and an additional parameter, providing extra safety checks in the form of explicit runtime-constraints as defined in the C11 standard. The fopen_s() function provides a new mode character, u which may precede any of the previously defined modes starting with the character w or a. See INCITS/ISO/IEC 9899:2011.
Implementation specific details for fopen_s() include the following:
Files opened for writing are opened with exclusive, (or non-shared), access. The file permission for the file will prevent other system users from accessing the file, that is S_IRUSR | S_IWUSR flags if the file is being created and the first character of the mode string is not u. For more information, see the chmod(2) man page. If the file is being created and first character of the mode string is u, the file shall have the system default file access permissions.
A runtime-constraint violation will be generated if either streamptr, filename, or mode is a null pointer.
Return Values
Upon successful completion, fopen() returns a pointer to the object controlling the stream. Otherwise, a null pointer is returned and errno is set to indicate the error.
The fopen() function may fail and not set errno if there are no free stdio streams.
If the fopen_s() function succeeds in opening a file, it returns zero. Otherwise, a non-zero value is returned if fopen_s() failed to open the file or if a runtime-constraint violation was encountered.
Errors
The fopen() and fopen_s() functions will fail if:
Search permission is denied on a component of the path prefix, or the file exists and the permissions specified by mode are denied, or the file does not exist and write permission is denied for the parent directory of the file to be created.
A signal was caught during the execution of fopen().
The named file is a directory and mode requires write access.
Too many symbolic links were encountered in resolving filename.
There are <OPEN_MAX> file descriptors currently open in the calling process.
The length of the filename exceeds PATH_MAX or a pathname component is longer than NAME_MAX.
The maximum allowable number of files is currently open in the system.
A component of filename does not name an existing file or filename is an empty string.
The directory or file system that would contain the new file cannot be expanded, the file does not exist, and it was to be created.
A component of the path prefix is not a directory.
The named file is a character special or block special file, and the device associated with this special file does not exist.
The current value of the file position cannot be represented correctly in an object of type fpos_t.
The named file resides on a read-only file system and mode requires write access.
The fopen() function may fail if:
The value of the mode argument is not valid.
<FOPEN_MAX> streams are currently open in the calling process.
<STREAM_MAX> streams are currently open in the calling process.
Pathname resolution of a symbolic link produced an intermediate result whose length exceeds <PATH_MAX>.
Insufficient storage space is available.
The file is a pure procedure (shared text) file that is being executed and mode requires write access.
The fopen_s() function will fail if:
Null pointer is passed.
Usage
The fopen() function has a transitional interface for 64-bit file offsets. For more information, see the lf64(7) man page.
fopen, fopen_s
1) Opens a file indicated by filename and returns a pointer to the file stream associated with that file. mode is used to determine the file access mode.
2) Same as (1) , except that the pointer to the file stream is written to streamptr and the following errors are detected at runtime and call the currently installed constraint handler function:
- streamptr is a null pointer
- filename is a null pointer
- mode is a null pointer
As with all bounds-checked functions, fopen_s is only guaranteed to be available if __STDC_LIB_EXT1__ is defined by the implementation and if the user defines __STDC_WANT_LIB_EXT1__ to the integer constant 1 before including stdio.h .
Parameters
| filename | — | file name to associate the file stream to |
| mode | — | null-terminated character string determining file access mode File access mode string Meaning Explanation Action if file already exists Action if file does not exist "r" read Open a file for reading read from start failure to open "w" write Create a file for writing destroy contents create new "a" append Append to a file write to end create new "r+" read extended Open a file for read/write read from start error "w+" write extended Create a file for read/write destroy contents create new "a+" append extended Open a file for read/write write to end create new File access mode flag "b" can optionally be specified to open a file in binary mode. This flag has no effect on POSIX systems, but on Windows it disables special handling of ‘\n’ and ‘\x1A’. On the append file access modes, data is written to the end of the file regardless of the current position of the file position indicator. The behavior is undefined if the mode is not one of the strings listed above. Some implementations define additional supported modes (e.g. Windows). In update mode (‘+’), both input and output may be performed, but output cannot be followed by input without an intervening call to fflush, fseek, fsetpos or rewind, and input cannot be followed by output without an intervening call to fseek, fsetpos or rewind, unless the input operation encountered end of file. In update mode, implementations are permitted to use binary mode even when text mode is specified. File access mode flag "x" can optionally be appended to "w" or "w+" specifiers. This flag forces the function to fail if the file exists, instead of overwriting it. (C11) When using fopen_s or freopen_s, file access permissions for any file created with "w" or "a" prevents other users from accessing it. File access mode flag "u" can optionally be prepended to any specifier that begins with "w" or "a", to enable the default fopen permissions. (C11) |
| streamptr | — | pointer to a pointer where the function stores the result (an out-parameter) |
Return value
1) If successful, returns a pointer to the new file stream. The stream is fully buffered unless filename refers to an interactive device. On error, returns a null pointer . POSIX requires that errno be set in this case.
2) If successful, returns zero and a pointer to the new file stream is written to *streamptr . On error, returns a non-zero error code and writes the null pointer to *streamptr (unless streamptr is a null pointer itself).
Name already in use
cpp-docs / docs / c-runtime-library / reference / fopen-s-wfopen-s.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Opens a file. These versions of fopen , _wfopen have security enhancements, as described in Security features in the CRT.
pFile
A pointer to the file pointer that will receive the pointer to the opened file.
mode
Type of access permitted.
Zero if successful; an error code on failure. For more information about these error codes, see errno , _doserrno , _sys_errlist , and _sys_nerr .
| pFile | filename | mode | Return Value | Contents of pFile |
|---|---|---|---|---|
| NULL | any | any | EINVAL | unchanged |
| any | NULL | any | EINVAL | unchanged |
| any | any | NULL | EINVAL | unchanged |
The fopen_s and _wfopen_s functions can’t open a file for sharing. If you need to share the file, use _fsopen or _wfsopen with the appropriate sharing mode constant—for example, use _SH_DENYNO for read/write sharing.
The fopen_s function opens the file that’s specified by filename . _wfopen_s is a wide-character version of fopen_s ; the arguments to _wfopen_s are wide-character strings. _wfopen_s and fopen_s behave identically otherwise.
fopen_s accepts paths that are valid on the file system at the point of execution; UNC paths and paths that involve mapped network drives are accepted by fopen_s as long as the system that’s executing the code has access to the share or mapped network drive at the time of execution. When you construct paths for fopen_s , don’t make assumptions about the availability of drives, paths, or network shares in the execution environment. You can use either forward slashes (/) or backslashes (\) as the directory separators in a path.
These functions validate their parameters. If pFile , filename , or mode is a null pointer, these functions generate an invalid parameter exception, as described in Parameter validation.
Always check the return value to see if the function succeeded before you do any further operations on the file. If an error occurs, the error code is returned, and the global variable errno is set. For more information, see errno , _doserrno , _sys_errlist , and _sys_nerr .
By default, this function’s global state is scoped to the application. To change it, see Global state in the CRT.
fopen_s supports Unicode file streams. To open a new or existing Unicode file, pass a ccs flag that specifies the desired encoding to fopen_s , for example:
fopen_s(&fp, «newfile.txt», «w+, ccs=UNICODE»);
Allowed values of the ccs flag are UNICODE , UTF-8 , and UTF-16LE . If no value is specified for ccs , fopen_s uses ANSI encoding.
If the file already exists and is opened for reading or appending, the byte order mark (BOM), if present in the file, determines the encoding. The BOM encoding takes precedence over the encoding that’s specified by the ccs flag. The ccs encoding is only used when no BOM is present or if the file is a new file.
[!NOTE] BOM-detection only applies to files that are opened in Unicode mode; that is, by passing the ccs flag.
The following table summarizes the modes for various ccs flag values that are given to fopen_s and for BOMs in the file.
Encodings used based on ccs flag and BOM
| ccs flag | No BOM (or new file) | BOM: UTF-8 | BOM: UTF-16 |
|---|---|---|---|
| UNICODE | UTF-8 | UTF-8 | UTF-16LE |
| UTF-8 | UTF-8 | UTF-8 | UTF-16LE |
| UTF-16LE | UTF-16LE | UTF-8 | UTF-16LE |
Files that are opened for writing in Unicode mode have a BOM written to them automatically.
If mode is «a, ccs=UNICODE» , «a, ccs=UTF-8» , or «a, ccs=UTF-16LE» , fopen_s first tries to open the file with both read access and write access. If successful, the function reads the BOM to determine the encoding for the file; if unsuccessful, the function uses the default encoding for the file. In either case, fopen_s then reopens the file with write-only access. (This behavior applies to a mode only, not a+ .)
The character string mode specifies the kind of access that’s requested for the file, as follows.
| mode | Access |
|---|---|
| «r» | Opens for reading. If the file doesn’t exist or can’t be found, the fopen_s 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 end-of-file (EOF) marker before new data is written to the file. Creates the file 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 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. The EOF marker isn’t restored after writing is completed. Creates the file if it doesn’t exist. |
When a file is opened by using the «a» or «a+» access type, all write operations occur at the end of the file. The file pointer can be repositioned by using fseek or rewind , but it’s always moved back to the end of the file before any write operation is carried out so that existing data can’t be overwritten.
The «a» mode doesn’t remove the EOF marker before appending to the file. After appending has occurred, the MS-DOS TYPE command only shows data up to the original EOF marker and not any data that’s appended to the file. The «a+» mode does remove the EOF marker before appending to the file. After appending, the MS-DOS TYPE command shows all data in the file. The «a+» mode is required for appending to a stream file that is terminated with the CTRL +Z EOF marker.
When the «r+» , «w+» , or «a+» access type is specified, both reading and writing are allowed. (The file is said to be open for «update».) However, when you switch from reading to writing, the input operation must come across an EOF marker. If there’s no EOF marker, you must use an intervening call to a file-positioning function. The file-positioning functions are fsetpos , fseek , and rewind . When you switch from writing to reading, you must use an intervening call to either fflush or to a file-positioning function.
Starting in C11, you can append «x» to «w» or «w+» to cause the function fail if the file exists, instead of overwriting it.
In addition to the values above, the following characters can be included in mode to specify the translation mode for newline characters:
| mode modifier | Translation mode |
|---|---|
| t | Open in text (translated) mode. |
| b | Open in binary (untranslated) mode; translations involving carriage-return and line feed characters are suppressed. |
In text (translated) mode, CTRL +Z is interpreted as an end-of-file character on input. In files opened for reading/writing with «a+» , fopen_s checks for a CTRL +Z at the end of the file and removes it, if possible. It’s removed because using fseek and ftell to move within a file that ends with a CTRL +Z, may cause fseek to behave improperly near the end of the file.
Also, in text mode, carriage return/line feed (CRLF) combinations are translated into single line feed (LF) characters on input, and LF characters are translated to CRLF combinations on output. When a Unicode stream-I/O function operates in text mode (the default), the source or destination stream is assumed to be a sequence of multibyte characters. The Unicode stream-input functions convert multibyte characters to wide characters (as if by a call to the mbtowc function). For the same reason, the Unicode stream-output functions convert wide characters to multibyte characters (as if by a call to the wctomb function).
If t or b isn’t given in mode , the default translation mode is defined by the global variable _fmode . If t or b is prefixed to the argument, the function fails and returns NULL .
For more information about using text and binary modes in Unicode and multibyte stream-I/O, see Text and binary mode file I/O and Unicode stream I/O in text and binary modes.
| mode modifier | Behavior |
|---|---|
| c | Enable the commit flag for the associated filename so that the contents of the file buffer are written directly to disk if either fflush or _flushall is called. |
| n | Reset the commit flag for the associated filename to «no-commit.» This flag is the default. It also overrides the global commit flag if you link your program with COMMODE.OBJ . The global commit flag default is «no-commit» unless you explicitly link your program with COMMODE.OBJ (see Link options). |
| N | Specifies that the file isn’t inherited by child processes. |
| 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 isn’t flushed to disk. |
| D | Specifies a file as temporary. It’s deleted when the last file pointer is closed. |
| ccs=UNICODE | Specifies UNICODE as the encoded character set to use for this file. Leave unspecified if you want ANSI encoding. |
| ccs=UTF-8 | Specifies UTF-8 as the encoded character set to use for this file. Leave unspecified if you want ANSI encoding. |
| ccs=UTF-16LE | Specifies UTF-16LE as the encoded character set to use for this file. Leave unspecified if you want ANSI encoding. |
Valid characters for the mode string used in fopen_s and _fdopen correspond to oflag arguments used in _open and _sopen , as follows.
| Characters in mode string | Equivalent oflag value for _open / _sopen |
|---|---|
| a | `_O_WRONLY |
| a+ | `_O_RDWR |
| R | _O_RDONLY |
| r+ | _O_RDWR |
| w | _O_WRONLY (usually `_O_WRONLY |
| w+ | _O_RDWR (usually **`_O_RDWR |
| b | _O_BINARY |
| t | _O_TEXT |
| c | None |
| n | None |
| S | _O_SEQUENTIAL |
| R | _O_RANDOM |
| t | _O_SHORTLIVED |
| D | _O_TEMPORARY |
| ccs=UNICODE | _O_WTEXT |
| ccs=UTF-8 | _O_UTF8 |
| ccs=UTF-16LE | _O_UTF16 |
The c , n , and t mode options are Microsoft extensions for fopen_s and _fdopen and shouldn’t be used where you want ANSI portability.
If you’re using rb mode, memory mapped Win32 files might also be an option if you don’t need to port your code, you expect to read much of the file, or you don’t care about network performance.
| Function | Required header | C++ header |
|---|---|---|
| fopen_s | <stdio.h> | <cstdio> |
| _wfopen_s | <stdio.h> or <wchar.h> | <cstdio> |
For more information on standards conformance and naming conventions in the C runtime library, see Compatibility.
What is fopen_s in C?
Get Educative’s popular interview prep course for free.
The fopen_s function in C is used to securely open files in different modes such as reading and writing. It is secure as it performs robust security checks on the arguments passed to it. For example, it would return an error if the pointer passed to it was NULL . Similarly, it requires the file access mode to be specified in its arguments to set the appropriate permission based on user type.
The fopen_s function is only available since the C11 standard. Otherwise, we can not use the function. So make sure that you have C11 enabled on your system!