通过fgets获得EOF

我正在写一个执行一些authentication操作的函数。 我有一个文件与所有的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 */ } /*...*/ } 

我如何pipe理EOF到达? 我看到,当到达EOF时, fgets不再编辑usr_psw_line,但是不返回NULL指针。 如果到达EOF,则意味着在用户文件和循环中断中找不到匹配项。

有人可以给我一些提示或build议吗?

当它到达文件结尾或错误条件时, fgets()返回一个空指针。

EOF是一个宏,它指定了某些其他函数在类似条件下返回的值;它不仅仅是“文件结尾”这个短语的缩写)。

你忽略了fgets()返回的结果。 不要这样做。

请注意,只是检查feof(fd)不会做你想要的。 如果到达文件末尾, feof()将返回一个真正的结果。 如果你遇到一个错误, feof()仍然返回false,如果你使用feof()来决定你什么时候完成的话,你会得到一个无限循环。 直到读取输入失败之后才会返回true。

大多数C输入函数返回一些特殊的值来表示没有更多的东西要读。 对于fgets()它是NULL ,对于fgetc()EOF ,等等。 如果你喜欢,你可以在之后调用feof()和/或ferror()来确定为什么没有更多的东西要读。

你可能想在你的循环中尝试这样的事情:

 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标记或文件上有任何错误,则循环将终止。 我相信这是过度的,但这些测试一直为我工作。