Reading a File in C using fopen and fgetc


In C, you can use the standard library function fopen() to open a file, and then use the function fread() or fgets() to read the contents of the file.
Here is an example of how to read the contents of a file called "sample.txt" using the fgets() function:

This program demonstrates how to read the contents of a file in C using the fopen() and fgetc() functions.

  • The program starts by including the stdio.h header file, which contains the declarations of the functions used in the program.
  • In the main function, the program declares a file pointer "fp" and a character variable "c". The open() function is used to open the file "sample.txt" in read mode and assigns the returned pointer to the file pointer "fp".
  • If the file is not found or it cannot be opened, the fopen() function will return a null pointer, and the program uses an if statement to check if the file pointer is null, in which case it prints an error message "File Cant Open or File Not Found" and exit the program.
  • The program then enters an infinite loop, which uses the fgetc() function to read the next character in the file. The fgetc() function takes a file pointer as an argument and returns the next character in the file as an int.
  • The program compares the returned value with the EOF (End of File) macro, which is a constant defined in the stdio.h header file that indicates the end of the file. If the returned value is EOF, the loop breaks, otherwise the program uses the printf function to print the character read.
  • Finally, the program closes the file using the fclose() function and returns 0 to indicate that the program has executed successfully.

It's worth noting that the program does not handle any error that may happen during the reading process such as reading a file that does not exist or reading a file that is not in the current directory.

Source Code

//Read a File in C Programming
//r w a
#include<stdio.h>
int main()
{
    FILE *fp;
    char c;
    fp=fopen("sample.txt","r");
    if(fp==NULL)
    {
        printf("\nFile Cant Open or File Not Found..");
    }
    while(1)
    {
        c=fgetc(fp);
        if(c==EOF)
            break;
        printf("%c",c);
    }
    return 0;
}
 

sample.txt

Tutor Joes
Cherry Road
Salem - 7
9043017689
To download raw file Click Here

Output

Tutor Joes
Cherry Road
Salem - 7
9043017689

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C