【发布时间】:2013-03-19 15:09:52
【问题描述】:
我正在使用 C 和文件管理进行练习,我能够打开文件、在文件上写入记录、关闭文件,但是我无法找到已经写入的记录。这是我的练习:(案例 2 中的搜索)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main(){
struct info{
char name[40];
char sur[40];
};
struct info rec;
FILE *f1, *f2;
int sel, ser, res;
char cmp[40];
int cont=0;
f1=fopen("lis.txt","a+");
do{
do{
printf("1> Add account\n");
printf("2> Search account\n");
printf("3> Modify account\n");
printf("4> Exit\n");
printf("Type your choice -> ");
scanf("%d", &sel);
if(sel<1 || sel>4){
printf("ERROR: The choice isn't allowed\n");
}
}while(sel<1 || sel>4);
getchar();
switch(sel){
case 1:
printf("Insert new account\n");
printf("Write name: ");
fgets(rec.name, sizeof(rec.name), stdin);
printf("Write surname: ");
fgets(rec.sur, sizeof(rec.sur), stdin);
fputs(rec.name,f1);
fputs(rec.sur,f1);
fprintf(f1,"\n");
printf("Account added!\n");
break;
case 2:
printf("Search account\n");
printf("Write surname to search: ");
fgets(cmp, sizeof(cmp), stdin);
while(!feof(f1)){
if(strcmp(cmp,rec.sur)==0){
printf("ENT\n");
}
}
break;
// case 3:
// printf("Modify account\n");
// //funzione ricerca qua
// printf("Account modificato correttamente!\n");
// break;
case 4:
printf("Closing...\n");
break;
default:
printf("ERROR!\n");
break;
}
}while(sel!=4);
}
程序还没有完成,所以我稍后会修复很多未使用的东西。 它在 OpenVMS 上进行了测试。
【问题讨论】:
-
请明确您的问题(尤其是question)。
-
情况2中的循环,我想这是一个feof错误但我不知道如何解决
-
在案例 2 中,您如何期望该循环每次提前文件指针到达 EOF ?
-
标准循环是
while (fgets(cmp, sizeof(cmp), stdin) != 0) { ... }。只有在 I/O 函数报告 EOF(例如fgets()返回 NULL)后,才使用feof()来区分 EOF 和 I/O 错误。基本上,如果你忘记了feof()的存在,你就不会出错。 -
@AlessioMTX,请阅读this StackOverflow thread 以获取有关您的
feof()问题的更多信息。
标签: c file-management