【发布时间】:2013-03-07 05:15:48
【问题描述】:
我正在编写一个执行某些身份验证操作的函数。我有一个包含所有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 但既不返回 NULL 指针。如果达到 EOF,则意味着在用户文件中找不到匹配项并且循环中断。
谁能给我一些提示或建议?
【问题讨论】:
-
如果在没有读取任何字符的情况下到达文件末尾,
fgets必须返回NULL。无论如何,您可以在fgets没有阅读任何内容之后检查feof(fd)。 -
恐怕没有设置EOF。我只写了一个里面有记录的文件。我还应该明确设置EOF吗?你是怎么做到的?
-
不就是读到文件尾吗?您不设置 EOF,如果到达文件末尾,则下一次尝试读取文件将在
*fd中设置标志,因此如果一切正常,feof(fd)将返回 true。如果一切都无法正常工作,嗯。 -
EOF是一个条件,而不是流的一部分。想象溪流是水龙头里的水。当您打开水龙头直到它耗尽时,您是否会得到更多水(另一种颜色?)以表示没有更多水了?