Question

I have a file which is opened for both write/read (fopen(name,"wb+")) which contains a load of the struct below

struct pedia
{
    int code;
    char descr[50];
    int TM;
    int pos;
    int flag;
};

The whole file is initialized with codes from 0 to the size of the file (user gives the size)flags equal to 0 ,descr=" " and TM=pos=-1

When i ask the user to write the # of the registration he wants to update and i print the struct which is saved there it s printed correctly.

Also when i call the input function in which the user sets new values for every variable in the struct i print the code,descr etc. right after and they are changed successfully .

However when i use fwrite to write the struct to the file it only writes 1 item successfully in the file.

void fileupdate(FILE *f,int filesize)
{
     struct pedia *field;
     field=(struct pedia *)malloc(sizeof(struct pedia));
     int k,key;
     char opt[5];
     int num=0;

     while(1)
     {
         puts("\nUPDATE\n");

         printf("\nType the # of the registration you want to update (key must be between 0 and %d) \n\nkey:",filesize);

         scanf("%d",&key);
         getchar();

         if(key>=0 && key<=filesize)
         {
             fseek(f,sizeof(struct pedia)*key,SEEK_SET);
             fread(field,sizeof(struct pedia),1,f);

             printf("%d,%s,%d,%d,%d\n",field->code,field->descr,field->TM,field->pos,field->flag);

             if(field->flag==0)
             {
                  puts("type yes to register new info or no to cancel the update\n");
                  fgets(opt,sizeof(char)*5,stdin);

                  if(isspace(*(opt+strlen(opt)-1)))
                *(opt+strlen(opt)-1)='\0';

                  if(strcmp(opt,"yes"))
                continue;

                  printmask();
                  input(&field);

                  num=fwrite(field,sizeof(struct pedia),1,f);
                  printf("\n%d,%s,%d,%d,%d\n",field->code,field->descr,field->TM,field->pos,field->flag);

                  printf("num=%d\n",num);
        }
    }
}
Was it helpful?

Solution

There is no fseek() between fread() and fwrite(), so fwrite() doesn't overwrite the struct you wanted to update but the next one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top