Read File in C


A file represents a sequence of bytes, regardless of it being a text file or a binary file. C programming language provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices.

You can use the fopen( ) function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream.

   Syntax :
        int *ptr = fopen ( " file_path " , " mode " ) ;
         r -> Read Mode
   Example :
        int *ptr = fopen ( " sample.txt " , " r " ) ;

  • Open the file using the fopen() function
  • Open the text file in read " r " mode
  • Using fgetc() function, read next character from text file into a string.
  • It returns the character (ASCII value) read from the file
  • This function returns a constant EOF (-1) when there is unsuccessful read
  • The file should be closed after reading using fclose() function.

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