File Handling in C

Fgets Code:

#include<stdio.h>
int main()
{
    FILE *fp;
    fp=fopen("a.txt","r"); //apend mode

    if(fp==NULL)
    {
        printf("unable to open file\n");
        return 1;
    }
//file opened successfully
    char names[80];

    while(1)
    {
        fgets(names,80,fp);
        printf("%s",names);
        if(feof(fp))
            break;
    }

    fclose(fp);
    //printf("Success\n");
    return 0;
}

Fgetc Code:

#include<stdio.h>
int main(){
FILE *fp;

fp=fopen("a.txt","r");
if(fp==NULL)
{
    printf("unable to open");
    return 0;
}
char ch;
ch=fgetc(fp); //char by char

while(!feof(fp)){
    printf("%c",ch);
    ch=fgetc(fp);
}
fclose(fp);
return 0;
}

Fscanf code:

#include<stdio.h>
int main(){

FILE *fp;
fp=fopen("names.txt","r");
if(fp==NULL)
{
printf("unable to open file\n");
return 0;
}
char name[80];
int salary;
while(1){
    fscanf(fp," %[^,],%d",name,&salary);
    printf("%s name gets %d per hour\n",name,salary);
    if(feof(fp)){
        break;
    }
}


return 0;
}

 

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published.