c - 如何在C语言中查找文本文件中的字符串?

标签 c string file text

我需要读取文本文件中的字符串序列并从中提取信息。该文件包含游戏角色的名称和 ID。我需要为每个 HeroID 获取其各自的英雄名称(“url”标签),然后将其存储到链接列表中,但在处理文本文件时,我在 C 语法方面遇到了很多困难。具体来说,我不知道如何搜索 HeroID,获取相应的编号和 url 并将其存储到链接列表中。

这是我唯一能够编写的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct s_hero{
    char name[30];
    int id;
    char attr[3];
    struct s_hero* next;
} type_hero;

type_hero* initialize(void){
    return NULL;
}

int main(){
    type_hero* hero = initialize();
    FILE *fp = fopen("npc_heroes.txt", "rt");

    return 0;
}

这是我必须阅读的文本文件:http://notepad.cc/howtofindthestrings

最佳答案

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

typedef struct s_hero {
    char name[30];
    int id;
    char attr[3];
    struct s_hero* next;
} type_hero;

type_hero* initialize(void){
    return NULL;
}

char *strip_dq(char *str){
    char *from, *to;

    for(from = to = str; *from ; ++from){
        if(*from != '"')
            *to++ = *from;
    }
    *to = '\0';
    return str;
}

type_hero *new_hero(char *name, int id){
    type_hero *hero = calloc(1, sizeof(*hero));
    strcpy(hero->name, name);
    hero->id = id;
    return hero;
}

void print_list(type_hero *top){
    while(top){
        printf("%d:%s\n", top->id, top->name);
        top = top->next;
    }
    printf("\n");
}

void drop_list(type_hero *top){
    if(top){
        drop_list(top->next);
        free(top);
    }
}

int main(){
    type_hero *hero = new_hero("", 0);//dummy
    type_hero *curr = hero;
    FILE *fp = fopen("npc_heroes.txt", "rt");
    char buff[128];
    while(1==fscanf(fp, "%127s", buff)){
        if(strcmp(buff, "\"HeroID\"")==0){//label
            fscanf(fp, "%s", buff);//data
            int id = atoi(strip_dq(buff));
            while(1==fscanf(fp, "%127s", buff) && strcmp(buff, "\"url\"")!=0)
                ;//skip
            fscanf(fp, "%s", buff);//data
            //char name[30];
            //strcpy(name, strip_dq(buff));
            curr = curr->next = new_hero(strip_dq(buff), id);
        }
    }
    curr = hero;
    hero = curr->next;
    free(curr);//drop dummy

    print_list(hero);
    drop_list(hero);
    return 0;
}

关于c - 如何在C语言中查找文本文件中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24848318/

相关文章:

c++ - 是什么让二进制流如此特别?

c - ATMEGA 328P 变频

C++ 需要一些关于 Pig Latin 字符串的建议

.NET 如何检查路径是否是文件而不是目录?

c - 指针和字符数组

javascript - jquery 追加在 IE 中不起作用在 FF 中工作正常

java - 如何转换java中的默认文件路径?

c - C中的无限递归

c++ - 如何使图片适合静态控件 vc++ win32

C将字符分配给结构