FAT | RFS | XFS | ZFS

freopen()

PROTOTYPE

#include <stdio.h>

FILE *freopen(const char *path, const char *mode, FILE *file);

DESCRIPTION

freopen() flushes the stream identified by file, ignoring any errors. If path is NULL, the referenced file control block is reinitialized, without closing the file, and its access mode is set to read-only, write-only, read-write, or append, as specified by mode.

If path is not NULL, the file indicated by file is closed, ignoring any errors, and a file is opened or created as by fopen(path, mode). Paths starting with ‘/’ are absolute. Otherwise they are relative to the CWD.

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()). 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, freopen() returns file. The file’s error and end-of-file flags are cleared and the current position is set to the file’s beginning. 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.
EBADF path equals NULL and file is not the handle of an open file.
EEXIST mode includes ‘x’ (plus ‘w’ or ‘a’) and the file already exists.
EFAULT 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.
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

  /*-------------------------------------------------------------------*/
  /* Reopen file and ensure EOF gets cleared.                          */
  /*-------------------------------------------------------------------*/
  if (freopen("/flash/new_tmp.txt", "r+", file) == NULL)
    error("freopen() failed");
  if (feof(file))
    error("feof() failed");

  ...

  /*-------------------------------------------------------------------*/
  /* Use freopen() to change file handle's mode from "w+" to "r".      */
  /*-------------------------------------------------------------------*/
  if (freopen(NULL, "r", file) == NULL)
    error("freopen() failed");