Skip to content

File Access

The stdio.h contains a typedef1 of a struct2 called FILE.
The fopen(const char*, const char*) function takes two arguments.

  1. Name of the file to be opened.
  2. The mode in which file needs to be opened in.
    • r for read.
    • w for write.
    • a for append.

If there is any error while opening the file, fopen(const char*, const char*) returns NULL.
There are two other functions as well.

int getc(FILE* file_ptr); // (1)!
int putc(char c, FILE* file_ptr); // (2)!
  1. Gets a char and moves the pointer one character ahead in the buffer in which file's contents exist.
  2. Writes a char to the buffer containing file's contents.

There are 3 const file pointers which are opened by the Operating System when a C program is ran.

  • stdin
  • stdout
  • stderr

Then, fclose(FILE*) is used to disconnect the program from the file.

References


  1. Read more about typedef

  2. Read more about structs