C语言读取存储n条profile记录的二进制文件出现死循环问题求解
代码问题与修复方案
存在的问题
- 写入逻辑错误:循环内每次以
wb模式打开文件,wb模式会清空文件原有内容再写入,最终文件仅保留最后1条profile记录,之前的全部被覆盖。 - 读取前未重新打开文件:写入阶段结束后已经调用
fclose关闭了文件指针,读取阶段没有重新以rb模式打开目标文件,直接操作已关闭的野指针fp,属于非法内存访问,读取到的内容全是无效值。 fread返回值判断错误:fread返回值为成功读取的元素个数,读取到文件末尾/读取失败时返回0,而非EOF。原判断条件fread(...) != EOF永远为真,直接导致无限循环。- 读取前的文件有效性判断逻辑失效:未打开文件就判断
fp==NULL,此时fp是野指针,判断逻辑完全不生效。
修复后的完整代码
#include <stdio.h> #include <stdlib.h> /*profile strucre */ struct profile { char name[30]; int phoneNumber; } pr; int main() { int rn; FILE *fp; printf("\nHow many profiles would you like to have?"); scanf("%d", &rn); struct profile p[rn]; for (int i = 0; i < rn; i++) { printf("\nEnter the name no %d: ", i+1); scanf("%s", p[i].name); printf("\nEnter the phone number %d: ", i+1); scanf("%d", &p[i].phoneNumber); } // 写入逻辑修正:仅打开一次文件 fp = fopen ("profiles.bin", "wb"); if (fp == NULL) { printf("File could not open for write"); exit(0); } for (int i = 0; i < rn; i++) { fwrite (&p[i], sizeof (p[i]), 1, fp); } fclose (fp); // 读取逻辑修正:先以rb模式打开文件 fp = fopen("profiles.bin", "rb"); if(fp==NULL) { printf("File could not open for read"); exit(0); } int j = 1; // fread判断条件修正:判断返回值是否等于预期读取的元素个数 while(fread(&pr,sizeof(pr),1,fp) == 1) { printf("\nRecord No:%d",j); printf("\n------------------"); printf("\nName:%s",pr.name); printf("\nPhone number:%d",pr.phoneNumber); printf("\n======================="); j++; } fclose(fp); return 0; }
内容的提问来源于stack exchange,提问作者phues
相关产品推荐
相关产品推荐

