fopen()
PROTOTYPE
#include <stdio.h>
FILE *fopen(const char *path, const char *mode);
DESCRIPTION
fopen() allocates a file control block and associates it with the file specified by path, optionally creating it. Paths starting with ‘/’ are absolute. Otherwise they are relative to the CWD. The file’s current position is set to its beginning, and its error and end-of-file flags are cleared.
mode specifies the file’s mode and must begin with one of the following characters, which used by itself sets the equivalent open() flags shown:
- ‘r’ - O_RDONLY
- ‘w’ - O_WRONLY | O_CREAT | O_TRUNC
- ‘a’ - O_WRONLY | O_CREAT | O_APPEND
mode may also include the following characters, some of which modify the initial open() flags:
- ‘b’ - no effect, supported for compatibility only
- ’+’ - replaces O_RDONLY and O_WRONLY with O_RDWR
- ‘x’ - if first character was ‘w’ or ‘a’, adds O_EXCL
- ’d’ - allows cache bypassing (non-standard)
- ‘a’ - enables asynchronous I/O buffering (non-standard)
- ‘n’ - eliminates overwrites (TargetXFS only, non-standard)
If the file exists and is truncated, its status change and data modification timestamps are updated. If a file is created, every timestamp of the new file and the status change and data modification timestamps of its parent directory are updated. The file’s user and group IDs are set to those of the calling task (as determined by FsGetId()) and its access permission bits are S_IRALL | S_IWALL, as modified by the file mode creation mask.
The caller needs search access to the path prefix and either write access to the parent directory if a file is created or every file access requested by mode if the file exists.
If successful, fopen() returns a file handle, an opaque pointer used by other API routines to reference the file. Otherwise, it sets errno and returns NULL.
ERROR CODES
| EACCES | No search access to the path prefix, file exists and a requested access is denied, or file is new and write access to parent directory is denied. |
| EEXIST | mode includes ‘x’ (plus ‘w’ or ‘a’) and the file already exists. |
| EFAULT | Either path or mode equals NULL. |
| EINVAL | mode or the leaf name in path is invalid. |
| EISDIR | path refers to a directory and mode requires write access. |
| ENAMETOOLONG | A name in path exceeds the effective maximum file name length. |
| EMFILE | No file control block is free. FOPEN_MAX files are currently open. |
| ENOENT | path is the empty string or includes file not found and not being created. |
| ENOSPC | No space is left on volume to create file. |
| ENOTDIR | One of the non-leaf path components is not a directory. |
| EROFS | The volume is read-only and write or append mode requested. |
EXAMPLE
FILE *file;
/*-----------------------------------------------------------------*/
/* Open file for reading. */
/*-----------------------------------------------------------------*/
file = fopen("/flash/temp.txt", "r");
if (file == NULL)
{
perror("fopen() failed");
return -1;
}