我正在编写一个执行某些身份验证操作的函数。我有一个文件,其中包含所有以以下结构构建的用户ID:密码:标志
对:
Users.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
必须返回NULL
。无论如何,在fgets
未读取任何内容后,您可以检查feof(fd)
。 - Daniel Fischer*fd
中的标志将被设置,因此如果一切正常,feof(fd)
将返回true。如果一切都不像应该那样工作,那就有点麻烦了。 - Daniel FischerEOF
是一种状态,而不是流的一部分。想象一下,流就像来自水龙头的水。当你打开水龙头直到它流尽时,你会得到更多的水(另一种颜色?)来表示没有更多的水了吗? - pmg