c - 逐节读取文件内容

标签 c file data-structures struct

我正在尝试将文件内容按节读取到可用的结构中,“#”符号开始一个节,而“.”符号开始一个节。符号结束它。一个例子是:

# Type name
bird
mammal
.
# Type effectiveness
VeryEffective
NotEffective
.

到目前为止,我可以读取第一种类型的内容,但是当我尝试读取第二种类型的内容时,我会不断重新读取第一种类型的内容。

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

int main() {
    typedef struct 
    {
        char types[1000];
        char effectiveness[1000];
    } sinFile; 
    sinFile record[1000];

    FILE* file; 
    char line[121];
    char period[10];
    char Type2[20];


    char* item; 
    char* item2;
    int i = 0;
    int j;


    file = fopen("Test3.txt", "r");

    while(fgets(line, 120, file)) {
        item = strtok(line, " ");
        strcpy(period, ".");
        strcpy(Type2, "# Type effectiveness");

        if (item[0] == '#' || item[0] == '.') {
            continue;
        } else {
            do {
                strcpy(record[i].types, line);
                i++;
            } while (strcmp(record[i].types, period) == 0);
        }


        for(j=0; strcmp(line, Type2) == 0; j++) { 
            do {
                strcpy(record[j].effectiveness, line);
                j++;
            } while (strcmp(record[j].effectiveness, period)== 0);
        }
    }

    fclose(file);

    printf("%s", record[1].effectiveness);
}

目前,record[1].types 给出的结果与 record[1].effectness 相同;即“哺乳动物”。我觉得我已经很接近了,但我不知道如何继续。

最佳答案

这段代码有很多问题。为了让它工作,应该使用类似这个示例的东西。

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

int main() {
    typedef struct 
    {
        char types[1000];
        char effectiveness[1000];
    } sinFile; 

    sinFile record[1000];

    FILE* file; 
    char line[121];
    char* bp; 
    int i=0, j=0;
    int state=0;

    file = fopen("Test3.txt", "r");

    while(fgets(line, 120, file)) {
        for(bp=line;isspace(*bp);bp++);
        if(state==0) {
            if(*bp=='#') {
                for(bp=line;isspace(*bp);bp++);
                item = bp;
                if(!strcmp(item,"Type name")) state=1;
                else if(!strcmp(item,"Type effectiveness")) state=2;
            }
        }
        else {
            if(*bp=='.') {
                state=0;
            }
            else if(state==1) {
                strcpy(record[i].types, bp);
                i++;
            }
            else if(state==2) {
                strcpy(record[j].effectiveness, bp);
                j++;
            }
        }
    }

    fclose(file);

    printf("%s", record[1].effectiveness);
}

但是使用这段代码,第一个 block 中的行必须与第二个 block 中的行相对应...使用没有 block 的键/值对会更简单。

关于c - 逐节读取文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40261895/

相关文章:

c - 从排序链表中一次性删除 "2 duplicated"个元素

c - 在c中编写跳转指令

C - 检查一个变量是否*没有*许多选项的最简洁的方法?

jQuery 不读取 xml 文件

java - Java中使用delete()方法删除文件

algorithm - 查找树中间附近的所有节点

performance - 客户端缓存有问题吗?

c - 了解 CPU 缓存和缓存行

c - lpc2148 RTC打印问题

C 中的命令行参数和 ftruncate