C program to read data from file using fgetc() function

 In this program we will learn how to read data from file...

EX: Write a C program to read data from file, C program to read data from file and display its contents.


  Program to read character from file:

  • file contents:

  Program to read data from file using fgetc() function:


#include<stdio.h>

void main()

{
    FILE *fp = NULL;

    fp = fopen("file.txt", "r");

    char ch = fgetc(fp);


    printf("The character i read from file is : %c", ch);
    
    fclose(fp);
}
    

  Output:

In above program we read character using fgetc() function. But, fgetc() function reads only one character. Now we will learn how to read string from file using fgetc().


  Program to read string from file using fgetc():

As we know fgetc() function reads only one character at a time. So, to read whole data from file we will run a while loop till the EOF(End Of File).



#include<stdio.h>
int main()
{
    FILE *fp = NULL;
    int ch;
    fp = fopen("file.txt", "r");
    
    while((ch = fgetc(fp))!=EOF)
    {
        printf("%c", ch);
    }
      
    fclose(fp);
    return 0;
}

 
 
  Above program shows the following Output:


Welcome to C file handling tutorials......



No comments:

Post a Comment

If you have any doubts, please discuss here...👇