【发布时间】:2018-03-10 08:30:54
【问题描述】:
文件格式如下
month day hour:min:sec process: message
例子:
Aug 13 12:20:34 automount[1478]: add_host_addrs: hostname lookup failed
我正在尝试逐行读取,并且对于读取的每一行,确定“消息”是否包含“失败”一词。
我运行时没有输出,请告诉我哪里出错了,谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INPUT_SIZE 80
int main()
{
FILE* file = fopen("logfile", "r");
char month;
int day, hour, min, sec;
char process[INPUT_SIZE];
char message[INPUT_SIZE];
char line[INPUT_SIZE];
if (fgets(line, INPUT_SIZE, file) == NULL)
{
perror("Error opening file");
}
else
{
sscanf("%3s %2d %2d:%2d:%2d %s %s", &month, &day, &hour, &min, &sec, &process, &message);
printf("%3s %2d %2d:%2d:%2d %s %s\n", month, day, hour, min, sec, process, message);
while (strstr(message, "fail"))
{
/* do something */
}
}
fclose(file);
if(line == NULL)
{
free(line);
}
return 0;
}
【问题讨论】:
-
1)
char month;-->char month[4];2)sscanf("%3s %2d %2d:%2d:%2d %s %s"...-->sscanf(line, "%3s %2d %2d:%2d:%2d %s %s"... -
您对
sscanf的调用完全错误 - 第一个参数是您的输入字符串,然后是格式 -
if(line == NULL) { free(line); }将被删除。只有free事物是动态创建的,例如使用mallocBTW:line永远不会变为 NULL -
3)
%s", &month-->%[^\n]", month -
为什么在 fgets 失败时会发出有关打开文件的错误消息?如果
fopen失败,请致电perror("logfile")。如果 fgets 失败,也调用perror("logfile")并期待与打开文件无关的错误消息。