Required knowledge
Basic Input Output, Do while loop, While loop, Pointers, File Handling
In the previous post, I explained how to use FILE pointer, fopen(), fputs() and fclose() function to create and write data into file.
In this post, we will continue further and will learn various functions in C programming to read and display file contents on console.
How to read data from a file?
C programming supports four predefined functions fgetc(), fgets(), fscanf() and fread() to read data from file. These functions are defined in stdio.h header file.
fgetc() - Used to read single character from file.
fgets() - Used to read string from file.
fscanf() - Use this to read formatted input from file.
fread() - Read block of raw bytes from file. Used to read binary files.
Step by step descriptive logic to read a file and display file contents.
- Open a file using
fopen() function and store its reference in a FILE pointer say fPtr.
You must open file in r(read) mode or atleast mode that support read access.
- Read content from file using any of these functions
fgetc(), fgets(), fscanf() or fread().
- Finally, close the file using
fclose(fPtr).
In this post I will explain how to read a file using fgetc() and fgets(). I will explain separately how to read formatted input and binary files.
How to read a file character by character using fgetc()?
int fgetc(FILE * stream);
Suppose data/file1.txt contains
Hurray!!! I learned to create file in C programming. I also learned to write contents to file. Next, I will learn to read contents from file on Codeforwin. Happy coding ;)