How to read a file in c









#include<stdio.h>
int main(){
    FILE *ptr; //It is file pointer
    char c;

    //opening the file in read mode in Linux os
     ptr = fopen("/root/Test/abc.c","r");

    //Opening the file in read mode in window os
    // ptr = fopen("C:\\Test\\abc.c","r");

    //Checking the path or file is valid or not and printing message
    if(ptr == NULL)
         printf("Error in opening the file");
    else
         printf("File has opened successfully in read mode");
   
    //Reading the each characters from file and printing it.
    do{
         c = getc(ptr);   //getting one character from file.
         printf("%c",c);  //printing the one character in console window
    }
    while(c != EOF);  //loop will terminate when end of file will reach.
   
    //closing the opened file
    fclose(ptr);                                                         
    return 0;
}








Post a Comment