我有一个为写入/读取 (fopen(name,"wb+")) 打开的文件,其中包含以下结构的负载
struct pedia
{
int code;
char descr[50];
int TM;
int pos;
int flag;
};
整个文件用从 0 到文件大小的代码初始化(用户给出大小)flags 等于 0 ,descr=" " 和 TM=pos=-1
当我要求用户写下他想要更新的注册号并打印保存在那里的结构时,它打印正确。
此外,当我调用输入函数时,用户为结构中的每个变量设置新值时,我会立即打印代码、描述等,并且它们已成功更改。
但是,当我使用 fwrite 将结构写入文件时,它只会在文件中成功写入 1 个项目。
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);
}
}
}