You're online now.

Hurray! you are online now.

File read in C | File Handling | How to read File

    int main(){
        char ch;
        FILE *f_pointer;
        f_pointer = fopen("./example.txt", "r");
        if(f_pointer == NULL){
            perror("Error Occurs!!");
        printf("Content of the File : \n");
        ch = fgetc(f_pointer);
        while (ch != EOF)
            printf("%c", ch);  // printing one by one characters from the file
            ch = fgetc(f_pointer);
        return 0;
  • ‘ch’ variable store the latest seek pointer where read the file.
  • f_pointer is a file pointer.
  • using the file fopen() function open the file. fopen() function take two arguments first argument is filename of file and second argument mode in which mode open the file.
  • check condition if (f_pointer == NULL) → perror("Error Occur") and perror() function also print the error that means whats error occur, and the exit to the program otherwise.
  • print content of the file.
  • ch == fgetc(f_pointer), ch hold the seek pointer where read the file.
  • and while ch ≠ EOF.
  • EOF → End of the file.
  • When ch is not reach to the end of the file then read the content and printing one by one character.
  • At last close the file using fclose() function.
🖤 0
Buy me coffee ☕



No comments here...