Read file contents and display them on the console with C.
fgetc() - To read single character from file.
fgets() - To read string from file.
fscanf() - To read formatted input from file.
fread() - Read block of raw bytes from file. Used to read binary files.
- Open a file using fopen() function and store its reference in a FILE pointer say fPtr
- Read content from file using any of these functions fgetc(), fgets(), fscanf() or fread().
- Finally, close the file using fclose(fPtr).
#include <stdio.h>
#include <stdlib.h>
int main()
{
/* File pointer to hold reference to our file */
FILE * fPtr;
char ch;
//Open file in r (read) mode.
//"data/file1.txt" is complete file path to read
fPtr = fopen("data/file1.txt", "r");
//fopen() return NULL if last operation was unsuccessful
if(fPtr == NULL)
{
// Unable to open file hence exit
printf("Unable to open file.\n");
printf("Please check whether file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}
//File open success message
printf("File opened successfully. Reading file contents character by character. \n\n");
do
{
/* Read single character from file */
ch = fgetc(fPtr);
/* Print character read on console */
putchar(ch);
} while(ch != EOF); /* Repeat this if last read character is not EOF */
/* Done with this file, close file to release resource */
fclose(fPtr);
return 0;
}
Output
File opened successfully.Reading file contents character by character.
I learned to create file in C programming.
I also learned to write contents to file.
0 Comments