Writing into and reading from a text file in C

We use fprintf() and fscanf() functions to write into the file and read from file respectively. fprintf()  writes the data to the text file and fscanf() reads the data from from file. The following example illustrates the concept….

Writing into the text file

#include<stdio.h>
#include<stdlib.h>
int main(){
    FILE *fp;
    struct emp{
        char name[40];
        int age;
        float bs;
    };
    struct emp e;
    //opening file in writing mode
    //this code creates a file named employ.dat if
    //it is not created or writes on the file if it
    //is already created.
    fp = fopen("employ.dat","w");
    if(fp == NULL){ //if file is not opened
        puts("Cannot open file");
        exit(1);
    }
    printf("\nEnter name, age and basic salary: ");
    scanf("%s %d %f", e.name, &e.age, &e.bs);
    //writes name age and basic salary to the file
    fprintf(fp, "%s %d %f\n", e.name, e.age, e.bs);
    fclose(fp); //close the file
    return 0;
}

Reading from the file

#include<stdio.h>
#include<stdlib.h>
int main(){
    FILE *fp;
    struct emp{
        char name[40];
        int age;
        float bs;
    };
    struct emp e;
    //opening file in writing mode
    //this code try to open the employ.dat
    //if it is already existed and returns null
    //to fp it is not existed
    fp = fopen("employ.dat","r");
    if(fp == NULL){ //if file is not opened
        puts("Cannot open file");
        exit(1);
    }
    printf("\nThe name, age and basic salary are: ");
    //search the file until end of file encountered
    while(fscanf(fp, "%s %d %f\n", e.name, &e.age, &e.bs)!=EOF){
        printf("%s %d %f\n",e.name,e.age,e.bs);
    }
    fclose(fp); //close the file
    return 0;
}
SHARE Writing into and reading from a text file in C

You may also like...

Leave a Reply

Your email address will not be published.

Share