Wednesday, July 20, 2011

Program to write data in a file and search data from file

/*Serial No.75     [swami54.cpp]*/

#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);
}

No comments:

Post a Comment

If you have any doubt, feel free to ask...