c,导入具有不同行的文本文件并处理这些行

时间:2013-03-06 11:42:56

标签: c text-files scanf

我试图创建一个读取聊天记录并计算一些数字的小程序。 事情是我不知道使用什么命令,因为线条不相同。 这是日志中的几行

[22:56:37]你的罢工被神奇的屏障吸收了!

[22:56:37]你错过了!

[22:56:37]你用你的明亮的arcanium加权大胡子斧攻击Tylaia,并造成70(-41)点伤害!

[22:56:37]你对Tylaia造成额外的19点伤害!

[22:56:37]你击中Tylaia造成66(-21)点伤害!

[22:56:37]你对Tylaia造成了17点额外伤害!

[22:56:37] Tniatha用明亮的暮色木头击打你的手,造成72点伤害!

[22:56:37] Tniatha对你造成额外的32点伤害!

[22:56:37] Tniatha对你造成8点额外伤害!

[22:56:37] Tniatha击中你造成8点伤害!

[22:56:37]你被笼罩在泥土中!

如何只导入“损坏”的行?

这是我到目前为止所拥有的;

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct{
    char your_self[15], char who_ever_else[15];
    int damage_done, damage_taken, healing_done, healing_taken;
} input;


int main(void){
    input *inputArray = malloc(1);
    read_log_file(&inputArray);
    return 0;
}

void read_log_file(input **inputArray, int *lineCount){
    char your_self[15], char who_ever_else[15];
    int damage_done, damage_taken, healing_done, healing_taken;

    FILE *inputFile;
    inputFile=fopen("chat.log", "r");
    if(inputFile = NULL){
        printf("File cant open");
        exit(1);
    }
}

想要做这样的事情; p

  (fscanf(inputFile, ".............."...

但是,因为每一行都不相同,所以我的变量会得到错误的值吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

查找“损坏”一词是否包含在一行中:

if (strstr(line, "damage") != NULL) {
    /* "damage" found */
}

答案 1 :(得分:1)

我最近写了一个类似的代码。猜猜这会有所帮助

char *match;

/* Read line by line - fgets reads only till a newline/ EOF - u can refer help*/
while (fgets(buffer, sizeof(buffer), fp))
{
    /* Search for pattern */
    match = strstr(buffer,"damage");

    if (match != NULL)
    {
                  //Do ur stuff
                 }
     }