我写了俩现成的函数,你直接调用就行
char *pFileName = "信息.dat";
// 将Person信息增加到文件中
// 返回值: 1 成功,0 失败
int writePersonToFile(Person *pPerson)
{
int ret = 0;
FILE *fp = fopen(pFileName, "ab");
if (NULL == fp)
{
printf("Open file %s error!\n", pFileName);
return ret;
}
if (1 != fwrite(pPerson, sizeof(Person), 1, fp))
{
printf("Write file %s error!\n", pFileName);
return ret;
}
fclose(fp);
return 1;
}
// 读取文件中指定位置的Person信息
// 返回值: 1 成功,0 失败
int readPersonFromFile(Person *pPerson, unsigned int pos)
{
int ret = 0;
unsigned int fileSize = 0;
FILE *fp = fopen(pFileName, "rb");
if (NULL == fp)
{
printf("Open file %s error!\n", pFileName);
return ret;
}
fseek(fp, 0, SEEK_END);
if (0 == (fileSize = ftell(fp)))
{
printf("File %s has no data!\n", pFileName);
return ret;
}
if (fileSize / sizeof(Person) <= pos)
{
printf("Data of position %d does not exist!\n");
return ret;
}
fseek(fp, pos * sizeof(Person), SEEK_SET);
if (1 != fread(pPerson, sizeof(Person), 1, fp))
{
printf("Read file %s error!\n", pFileName);
return ret;
}
fclose(fp);
return 1;
}
有问题联系我。
企鹅 287989240