File Access Functions - POSIX

The file access functions provide an API for performing a sequence of operations on a file located on a volume’s file system. The file object pointer returned when a file is opened is passed as an argument of all file access function, and the file object so referenced maintains information about the actual file (on the volume) and the state of the file access (see Figure - File state transitions). The file access state includes the file position (the next place data will be read/written), error conditions and (if file buffering is enabled) the state of any file buffer.

As data is read from or written to a file, the file position is incremented by the number of bytes transferred from/to the volume. The file position may also be directly manipulated by the application using the position set function (fs_fsetpos()), and the current absolute file position may be gotten with the position get function (fs_fgetpos()), to be later used with the position set function.

Figure - File state transitions


If file buffering is enabled (
FS_CFG_FILE_BUF_EN is DEF_ENABLED), then input/output buffering capabilities can be used to increase the efficiency of file reads and writes. A buffer can be assigned to a file using fs_setbuf() or fs_setvbuf(); the contents of the buffer can be flushed to the storage device using fs_fflush().The file maintains flags that reflect errors encountered in the previous file access, and subsequent accesses will fail (under certain conditions outlined here) unless these flags are explicitly cleared (using fs_clearerr()). There are actually two sets of flags. One reflects whether the file encountered the end-of-file (EOF) during the previous access, and if this is set, writes will not fail, but reads will fail. The other reflects device errors, and no subsequent file access will succeed (except file close) unless this is first cleared. The functions fs_ferror() and fs_feof() can be used to get the state of device error and EOF conditions, respectively.

If file buffering is enabled (FS_CFG_FILE_BUF_EN is DEF_ENABLED), then input/output buffering capabilities can be used to increase the efficiency of file reads and writes. A buffer can be assigned to a file using fs_setbuf() or fs_setvbuf(); the contents of the buffer can be flushed to the storage device using fs_fflush().

If a file is shared between several tasks in an application, a file lock can be employed to guarantee that a series of file operations are executed atomically. fs_flockfile() (or its non-blocking equivalent fs_ftrylockfile()) acquires the lock for a task (if it does not already own it). Accesses from other tasks will be blocked until a fs_funlockfile() is called. This functionality is available if FS_CFG_FILE_LOCK_EN is DEF_ENABLED.