C Program To Write Data In A File And Search Data From File

How to write a C Program To Write Data In A File And Search Data From File in C Programming Language ?


Solution For C Program :

/*C Program To Write Data In A File And Search Data From File.*/


#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<process.h>
void main()
{
int r,found;
struct stud
    {
    char name[30];
    int age;
    int roll_no;
    }st;
FILE *fp;
fp=fopen("test.dat","r+t");
        if(fp==NULL)
            {
            printf("\nCannot open file\n");
            exit(1);
            }

printf("enter role no:");
found=0;
scanf("%d",&r);

while((!feof(fp))&&(found))
    {
    fread(&st,sizeof(stud),1,fp);
    if(st.roll_no==r)
    {
    fseek(fp,-sizeof(stud),SEEK_CUR);
    printf("enter new name\n");
    scanf("%s",st.name);
    fwrite(fp,sizeof(stud),1,fp);
    found=1;
    }
    }
    if(!found)
    printf("record not present");
    fclose(fp);
}

You may also learn these C Program/Code :

C Program To Swap Two Numbers Without Using Third Variable



Learn More :