imagineracoon
imagineracoon

Reputation: 27

Editing a line in a file in C

I am creating this change function. void cha(struct cont x);, It will ask for the lname then check if its in the file. After that, It will edit.Asks for the lname and fname again. It works but it writes at the bottom of the file.

struct cont 
{
 char lname[20];
 char fname[20];
}s;

void cha(struct cont x)
    {
        FILE *fp;
        char lname[20];
        int flag=0;
        fp=fopen("database.dat","a+");
        if(fp==NULL)
        {
            printf("file error");
        }
        else
        {
            printf("\nenter lname: ");
            gets(lname);

            while(fscanf(fp,"%s %s",x.lname,x.fname)==2)
            {
                if(strcmp(lname,x.lname)==0)
                {
                    printf("enter lname: ");
                    gets(x.lname);
                    printf("enter fname: ");
                    gets(x.fname);

                    fseek(fp,-sizeof(x),SEEK_CUR);
                    fprintf(fp,"%s %s\n",x.lname,x.fname);
                    flag=1;
                    break;

                }
            }

            if(flag==1)
            {
                printf("success!");
            }

            else
            {
                printf("data not found.");
            }
        }
        fclose(fp);
    }

Upvotes: 0

Views: 80

Answers (2)

antonpuz
antonpuz

Reputation: 3316

Just write it to another file

FILE *newFile = fopen("newDatabase.dat","w");

if(strcmp(lname,x.lname)==0)
{
    //scan data to tmp var
    fprintf(newFile ,"%s %s\n",x2.lname,x2.fname);
}
else
{
    //write original var
    fprintf(newFile ,"%s %s\n",x.lname,x.fname);

}

you can then change the name of the new file to overwrite the old one if its important

Upvotes: 1

Gopi
Gopi

Reputation: 19864

fp=fopen("database.dat","r");

You have opened the file in read mode and you are trying to write to the file

fprintf(fp,"%s %s\n",x.lname,x.fname);

Use a+ to open the file in append mode.

gets() is no more a standard and use fgets() which takes care of buffer overflow.

Man says:

a+

Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.

Upvotes: 4

Related Questions