VOOZH about

URL: https://www.geeksforgeeks.org/c/how-to-read-from-a-file-in-c/

⇱ How to Read From a File in C? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Read From a File in C?

Last Updated : 17 Jun, 2024

File handing in C is the process in which we create, open, read, write, and close operations on a file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and many different C file operations in our program.

In this article, we will explore how to read from a file in C using standard library functions.

Read From a File in C

In C, we can read files using functions provided by the standard library such as fopen(), fgetc(), fgets(), and fread().

Steps To Read A File:

  • Open a file using the function fopen() and store the reference of the file in a FILE pointer.
  • Read contents of the file using any of these functions fgetc(), fgets(), fscanf(), or fread().
  • File close the file using the function fclose().

Lets try to read contents of the file test.txt that contains following content

GeeksforGeeks | A computer science portal for geeks

C Program to Read a File

Output

GeeksforGeeks | A computer science portal for geeks

In this program, we will read contents of the file using fgetc(). fgetc() reads characters pointed by the function pointer at that time. On each successful read, it returns the character (ASCII value) read from the stream and advances the read position to the next character. This function returns a constant EOF (-1) when there is no content to read or an unsuccessful read.



Comment