C Standard Library

C <stdio.h> - FILE Type



The C <stdio.h> FILE type is object type that identifies a C stream. It contains the information needed to control it, including a pointer to its buffer, its position indicator, end-of-file status indicator, error status indicator, binary/text mode indicator and all other state indicators.

FILE objects are usually created by a call to either fopen() or tmpfile() function, which both return a pointer to one of these objects. Its memory allocation is automatically managed and allocated when fopen() or tmpfile() function is used. The allocated resources are freed once either the stream is closed using fclose() or the program terminates normally.

When <stdio.h> header file is included, three objects of this type are automatically created, and pointers to them are declared: stdin, stdout and stderr, associated with the standard input stream, standard output stream and standard error stream, respectively.

In the <stdio.h> header file, it is defined as follows:

typedef /* unspecified */ FILE;            

Example:

Lets assume that we have a file called test.txt. This file contains following content:

This is a test file.
It contains dummy content.

In the example below, file is opened using fopen() function. If the return value of calling getc() function is not EOF, it starts reading characters the file one by one and writes the characters to output stream.

#include <stdio.h>
 
int main (){
  //open the file in read mode
  FILE *pFile = fopen("test.txt", "r");
  
  //first character in the file
  int c = getc(pFile);
  
  //if first character is not EOF, reads and writes
  //characters from the file until EOF is not reached
  while (c != EOF) {
    putchar(c);
    c = getc(pFile);
  }
  
  //close the file
  fclose(pFile);
  return 0;
}

The output of the above code will be:

This is a test file.
It contains dummy content.

❮ C <stdio.h> Library

5