我是C的新手,我需要从文本文件中获取特定信息。文本文件格式为:
2015-01-01 12:00:01 rossi S
2015-01-02 12:00:01 bianchi F
2015-01-02 12:00:20 bianchi F
2015-01-03 00:00:01 rossi S
2015-01-03 11:12:20 verdi F
这是结构声明
struct login_attempt{
int day, month, year, hour, minute, second;
char username[10];
char status;
}; struct login_attempt attempts[256];
这是不起作用的代码:
FILE *log_file = fopen("/Users/williambertarello/Desktop/Test/Test/log.txt", "r+");
if(log_file == NULL){
printf("\n No selected file \n");
}else{
for(int i = 0; i < total_login_attempts(log_file); i += 1){
int year =0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
char username[10];
char status;
int ret = fscanf(log_file, "%d-%d-%d %d:%d:%d %s %c", &year, &month, &day, &hour, &minute, &second, username, &status);
if(ret == 2){
attempts[i].year = year;
attempts[i].month = month;
attempts[i].day = day;
attempts[i].hour = hour;
attempts[i].minute = minute;
attempts[i].second = second;
attempts[i].status = status;
}
}
}
fclose(log_file);
此程序的目的应该是揭示服务器中无人值守的重复登录失败的潜在安全风险。
编辑: 在对if(ret == 2)不正确的一些建议之后,我尝试了这个,但它没有工作,因为调试的变量值是:
for(int i = 0; i < total; i += 1){
int ret = fscanf(log_file, "%d-%d-%d %d:%d:%d %s %c", &attempts[i].year, &attempts[i].month, &attempts[i].day, &attempts[i].hour, &attempts[i].minute, &attempts[i].second, attempts[i].username, &attempts[i].status);
}
Login attempt 0 -> {
day: 1265508352
month: 32767
year: -256879960
hour: 32767
minute: 1512161226
second: 0
}
答案 0 :(得分:2)
为什么要检查fscanf
aginst 2
的返回值?您正在阅读两个以上的参数,并且您希望获得8
次成功分配?