• For opening a file, fopen() function is used with the required access modes.
FILE *fp;/*variable fp is pointer to type FILE*/
 
fp = fopen("filename", "mode");
/*opens file with name filename , assigns identifier to fp */
  • fopen() return NULL if its unable to open the specified file.
  • File pointer fp points to the file resource.
    • contains all information about file.
    • Communication link between system and program.
  • An opened file is closed by passing the file pointer to fclose().
fclose(fp);

Different modes

  1. Reading mode (r) :
    • if the file already exists then it is opened as read-only.
    • sets up a pointer which points to the first character in it.
    • else error occurs.
  2. Writing mode (w) :
    • If the file already exists then its overwritten by a new file.
    • else a new file with specified name is created.
  3. Appending mode (a) :
    • If the file already exists then it is opened.
    • else new file created.
    • sets up a pointer that points to the last character in it.
    • any new content is appended after existing content.

Additional modes

  • r+ opens file for both reading/writing an existing file, doesn’t delete the contents of if the existing file.
  • w+ opens file for reading and writing a new file. Overwrite if the specified already exists.
  • a+ open file for reading and writing from the last character in the file.

Random access to a file

Data in a file is basically a collection of bytes. We can directly jump to a target byte-number in a file without reading previous data using fseek()

  • syntax: fseek(file-pointer, offset, position);
  • position: 0 (beginning), 1 (current), 2 (end)
  • offset: number of locations to move from specified position
fseek(fp, -m, 1); // move back by m bytes from current
fseek(fp, m, 0); // move to (m+1)th byte in file
  • ftell(fp) returns current byte position in file.
  • rewind(fp) resets position to start of file.