我正在编写一个执行一些身份验证操作的函数。我有一个包含所有user_id:password:flag对的文件,结构如下:
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,但都不会返回空指针。如果达到EOF,则意味着在用户文件中找不到匹配项,循环中断。
有人能给我一些提示或建议吗?
发布于 2013-03-19 03:54:32
当到达文件结尾或出现错误时,fgets()将返回一个空指针。
(EOF是一个宏,它指定某些其他函数在类似条件下返回的值;它不仅仅是短语“文件结束”的缩写。)
您忽略了fgets()返回的结果。别干那事。
请注意,仅检查feof(fd)并不能完成您想要的操作。如果到达文件的末尾,feof()将返回true结果。如果您遇到错误,feof()仍然返回false,并且如果您使用feof()来决定何时完成,您将得到一个无限循环。直到你读取输入失败后,它才会返回true。
大多数C输入函数都会返回一些特殊的值,表示没有更多的东西可读。对于fgets()是NULL,对于fgetc()是EOF,以此类推。如果您愿意,可以在事后调用feof()和/或ferror()来确定为什么没有更多内容可读。
发布于 2013-03-19 03:17:13
你可能想在你的循环中尝试这样的东西:
while(1)
{
memset((void*)usr_psw_line, 0, sizeof(USR_SIZE+PSW_SIZE+3+1));
if( !fgets(usr_psw_line, USR_SIZE+PSW_SIZE+3+1, fd)
|| ferror( fd ) || feof( fd ) )
{
break;
}
printf("%s\n", usr_psw_line);
fseek(fd, 1, SEEK_CUR);
/*EOF management*/
/*usr_id - password matching checking */
}使用额外的代码,如果fgets返回NULL (没有更多的数据要读取),或者如果您正在读取EOF标记或文件中有任何错误,则循环将终止。我相信这有点过头了,但这些测试对我来说一直都很有效。
https://stackoverflow.com/questions/15484106
复制相似问题