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.

C File Handling Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.