Saturday, November 22, 2014

C Standard IO Library

stdio provides a platform independent user buffering solution.  Files are referred by file pointer instead of the system level fd.  The file point type FILE is in cap because stdio as originally written as MACRO and thus follow the convention.

  • fopen - open a file and return a pointer to FILE.  The file opened is called a stream.
  • fdopen - open a file using fd
  • fclose - close file
  • fcloseall - close all streams
  • fgetc - read a char from a stream
  • fgets - reading multiple characters until a NEWLINE char or EOF is reached.  The \n will be stored as part of line read.  A NULL char will be added to the end of the string
  • fungetc - put a character (casted as unsigned int) into the stream.  You can issue more than one calls and the char are pushed back like a stack - so the next fread will return the last pushed char.  The standard defines only one push back is allowed.  Linux allows multiple push back as long as memory is available.  If fungetc is followed by a seek, the pushed back char will be lost because the buffer will be reused by a new block.
  • fread - reading binary data (in form of a structure, record) from the stream.  Caller pass the size of the structure and the number of structure to be read.  The function returns the number of structure read.  If the number is less than specified, it could be due to EOF reached or error is encountered during read.  Use ferror() or feof() to identify the condition.  Note that the program needs to assume the file is created (could be by another problem in another system) with same variable sizes, alignment, padding abd byte order.
  • fputc - write a byte
  • fputs - write a string
  • fwrite - writ binary data
  • fseek - advance the position in a stream.  Uses whence parameter to indicate if the offset provided represents the absolute position, relative to the current file position or to the end of file
  • fsetpos - like fseek with whence = SEEK_SET (absolute position).  This API is provided for non-Linux system that uses complex type to store file position.
  • rewind - set the position to the start of the stream
  • fgetpos - fseek does not return the current position like lseek.  This API acheive the requirement.
  • fflush - write out standard io buffer to the kernel buffer.
  • fileno - return the file descriptor of a stream.   Caution - do not intermix standard io with system IO call



No comments: