[英]Working with binary file - input order is wrong
以下代码接受用户输入并将数据添加到名为 match.bin 的二进制文件中。 第一次输入成功,但在第二次询问时,我无法先输入id。 它直接询问姓名,姓氏,工作和视图。 从我所见,代码应该可以正常工作,但我不明白为什么它不工作? 任何指导表示赞赏。 谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
unsigned int id; // person id
char name[20]; // person name
char surname[20]; // person surname
char job[20]; // job of person
int view; // match view number of person
}personData;
int main(void){
FILE *bfptr;
if((bfptr = fopen("match.bin", "wb"))== NULL){
puts("Could not open the file.");
}
else{
personData blankrecord = {0, "", "", "",0};
for(unsigned int i = 1; i<= 100; ++i)
fwrite(&blankrecord, sizeof(personData), 1 , bfptr);
fclose(bfptr);
}
if((bfptr = fopen("match.bin", "rb+"))==NULL){
puts("Could not open the file in rb+ mode.");
}
else{
personData person;
printf("%s","Enter the Id number (1 to 100, put 0 to end input). ");
scanf("%d", &person.id);
while(person.id != 0){
printf("%s", "Enther the Name, surname job and view:");
scanf("%5s %5s %5s %1d",person.name,person.surname,person.job,&person.view);
fseek(bfptr, (person.id - 1 )*sizeof(personData), SEEK_SET);
fwrite(&person, sizeof(personData), 1 , bfptr);
printf("%s", "Enter another Id: ");
scanf("%d", &person.id);
}
fclose(bfptr);
}
personData persontemp[100];
bfptr = fopen("match.bin", "rb");
for(int i = 0; i <100; i++){
fread(&persontemp[i], sizeof(persontemp[i]), 1 , bfptr);
printf("%i %s %s %s %i\n",persontemp[i].id,persontemp[i].name,persontemp[i].surname,persontemp[i].job,persontemp[i].view);
}
fclose(bfptr);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.