【问题标题】:How to find a string inside a text file in C?如何在C中的文本文件中查找字符串?
【发布时间】:2014-07-20 07:27:09
【问题描述】:

我需要读取文本文件中的一系列字符串并从中提取信息。该文件包含游戏角色的名称和 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

【问题讨论】:

  • 问题已经在堆栈溢出中有答案:stackoverflow.com/questions/10590114/…
  • @SujithKarivelil,虽然所谓的 dup 确实演示了如何在文件中查找字符串,但这个问题提出的解析问题可能更复杂;给stackoverflow.com/questions/10590114/… 的答案可能没有完全解决。我不认为你是对的。
  • 我可以将文本文件转换为单个字符串,然后用字符串函数搜索它吗?"
  • @RodrigoRonconiRichter 是的,您可以使用fread() 将文件数据读入缓冲区,然后使用strstr() 定位您要查找的字符串的第一次出现。 strstr 函数将返回一个指向第一次出现的字符串开头的指针。
  • 技术人员的名字("url") 不存在。

标签: c string file text


【解决方案1】:
#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;
}

【讨论】:

    猜你喜欢
    • 2013-04-18
    • 1970-01-01
    • 2018-05-18
    • 2015-07-14
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多