我正在编写一个函数来执行一些身份验证操作。我有一个包含所有结构如下的 user_id:password:flag
对的文件:
用户.txt
user_123:a1b2:0 user_124:a2b1:1 user_125:a2b2:2
这是代码:
int main(){
/*...*/
/*user_id, password retrieving*/
USRPSW* p = malloc(sizeof(USRPSW));
if(p == NULL){
fprintf(stderr, "Dynamic alloc error\n");
exit(EXIT_FAILURE);
}
memset((void*)p, 0, sizeof(USRPSW));
if(usr_psw_read(acc_sock_ds, p->user_id, USR_SIZE) <= 0){
printf("Failed read: connection with %s aborted.\n",
inet_ntoa(client_addr.sin_addr));
close(acc_sock_ds);
continue;
}
if(usr_psw_read(acc_sock_ds, p->password, PSW_SIZE) <= 0){
printf("Failed read: connection with %s aborted.\n",
inet_ntoa(client_addr.sin_addr));
close(acc_sock_ds);
continue;
}
/*Authentication through user_id, password*/
FILE *fd;
fd = fopen(USERSFILE, "r");
if(fd == NULL){
fprintf(stderr, "Users file opening error\n");
exit(EXIT_FAILURE);
}
char *usr_psw_line = malloc(USR_SIZE+PSW_SIZE+3+1);
if(usr_psw_line == NULL){
fprintf(stderr, "Dynamic alloc error\n");
exit(EXIT_FAILURE);
}
while(1){
memset((void*)usr_psw_line, 0, sizeof(USR_SIZE+PSW_SIZE+3+1));
fgets(usr_psw_line, USR_SIZE+PSW_SIZE+3+1, fd);
printf("%s\n", usr_psw_line);
fseek(fd, 1, SEEK_CUR);
/*EOF management*/
/*usr_id - password matching checking */
}
/*...*/
}
如何管理 EOF 到达?我看到当到达 EOF 时,fgets
不再编辑 usr_psw_line,但也不返回 NULL 指针。如果到达 EOF,则意味着在用户文件中找不到匹配项,循环中断。
有人可以给我一些提示或建议吗?
最佳答案
fgets()
在到达文件末尾或出现错误情况时返回空指针。
(EOF
是一个宏,它指定某些其他函数在类似条件下返回的值;它不仅仅是短语“文件结束”的缩写。)
您忽略了 fgets()
返回的结果。不要那样做。
请注意,仅检查 feof(fd)
不会执行您想要的操作。 feof()
如果您已到达文件末尾,则返回 true 结果。相反,如果您遇到错误,feof()
仍会返回 false,如果您使用 feof()
来决定何时执行操作,您就会陷入无限循环重做。直到您读取输入失败之后它才会返回 true。
大多数 C 输入函数返回一些特殊值以指示没有更多内容可读。对于 fgets()
,它是 NULL
,对于 fgetc()
,它是 EOF
,等等。如果愿意,您可以在之后调用 feof()
和/或 ferror()
来确定为什么没有更多内容可读。
关于c - 使用 fgets 到达 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15484106/