这是文件auth.txt (用户名密码)
paolo 1234
luca 0000
marci 1000
这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void onexit(char *u, char *p, char *l, FILE *f, int flag);
int main(int argc, char *argv[]){
FILE *fp;
char *tmp, *tmp2, *user, *pass, *line;
printf("Inserire utente: ");
if(scanf("%ms", &user) == EOF){
perror("scanf");
return EXIT_FAILURE;
}
printf("Inserire password: ");
if(scanf("%ms", &pass) == EOF){
perror("scanf");
onexit(user, NULL, NULL, NULL, 1);
return EXIT_FAILURE;
}
size_t max_length = strlen(user) + strlen(pass) + 3;
line = malloc(max_length);
if(line == NULL){
perror("malloc");
onexit(user, pass, NULL, NULL, 2);
return EXIT_FAILURE;
}
fp = fopen("/home/pol/auth.txt", "r");
if(fp == NULL){
printf("Errore apertura file\n");
onexit(user, pass, line, NULL, 3);
return EXIT_FAILURE;
}
while(!feof(fp)){
if(fgets(line, max_length , fp) == NULL){
perror("fgets");
onexit(user, pass, line, fp, 4);
return EXIT_FAILURE;
}
tmp = strtok(line, " ");
if(tmp == NULL){
perror("strtok");
onexit(user, pass, line, fp, 4);
return EXIT_FAILURE;
}
tmp2 = strtok(NULL, "\n");
if(tmp2 == NULL){
perror("strtok");
onexit(user, pass, line, fp, 4);
return EXIT_FAILURE;
}
if((strcmp(tmp,user) == 0) && (strcmp(tmp2,pass) == 0)){
printf("USER: %s - PASS: %s\n", tmp, tmp2);
onexit(user, pass, line, fp, 4);
return EXIT_SUCCESS;
}
else{
continue;
}
}
printf("no such user or pwd into DB\n");
onexit(user, pass, line, fp, 4);
return EXIT_FAILURE;
}
void onexit(char *u, char *p, char *l, FILE *f, int flag){
if(flag == 1){
free(u);
}
if(flag == 2){
free(u);
free(p);
}
if(flag == 3){
free(u);
free(p);
free(l);
}
if(flag == 4){
free(u);
free(p);
free(l);
fclose(f);
}
}
编辑:另一个问题!
如果我想测试我得到:luca
Inserire
utente:luca Inserire
密码:0000
strtok:成功
并且程序停止。它仅适用于第一个和第三个输入,但不适用于第二个!为什么??0000