Saturday, April 6, 2013

C Standard I/O Library

This refer to buffering in user space performed by application or standard library.  The C language does not provide any advanced I/O function.  In turn, the standard C library (stdio) provides a platform independently user buffering solution.  As buffering is maintained in user space rather than kernel space, there is a performance improvement. Standard I/O calls are not system calls.

The standard I/O routines use file pointer instead of file descriptor.  Inside C library, file pointer is mapped to file descriptor.  File pointer points to FILE typedef.

e.g. FILE * fopen(const char *path, const char *mode)

Mode includes
r = read
w = write
a = append
r+ = read and write, position at the start of file
w+ = read and write, truncate the file to size 0, positon at start of file
a+ = read and write, create file if does not exist, position at end of file

Other stdio routines include

fdopen - open using fd

fgetc/fputc - read/write a character from stream

ungetc - put a read character back to stream.  If multiple characters are unget, they are read in reverse order.  In other words, the last ungetc char will be returned first.  POSIX allows only 1 push back.  If a seek is performed before read, all pushed back characters will be lost.

fgets/fputs - read/write a string.  For read, a \0 character will be place at the end of the buffer.  Reading stop at EOF or a newline character is reached.  Newline \n is stored in the provided buffer

fread/fwrite - read/write specified number of elements (structures) from file.  This is reading the file as binary data.

fseek - seek to a particular position in the file
fsetpos - similar to seek.  This function is provided mainly for non-UNIX platform with have complex type representating stream positon.

rewind - reset the sream position to start of file

ftell - return the current stream position
fgetpos - pair with fsetpos above

fflush - write data from buffer to kernel space.  No gurarantee that the data are flushed to disk.  Issue fsync() after the flush to ensure data are written to disk.

fileno - obtain fd of a stream

No comments: