Home » C solved programs » C file handling programs

C - Read Content of a File using getc() using C Program

In this program (code snippet) you will learn how to read content of a file using getc() function in c programming language file handling?

In this example assume there is a file named "sample.txt" which contains text "This is sample.txt file document". By using c program file handling we will print characters on the output screen using getc() function.

C Code: Read Content of a File using getc() using C Program

/*C - Read Content of a File using getc() 
using C Program.*/
 
#include <stdio.h>
 
int main(){
 
    //file nane
    const char *fileName="sample.txt";
    //file pointer
    FILE *fp;
    //to store read character
    char ch;
     
    //open file in read mode
    fp=fopen(fileName,"r");
    if(fp==NULL){
        printf("Error in opening file.\n");
        return -1;
    }
    printf("Content of file\n");
    while((ch=getc(fp))!=EOF){
        printf("%c",ch);
    }
    fclose(fp);
     
    return 0;
}

Output

    Content of file 
    This is sample.txt file document.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.