区分文件中的数据C [英] Differentiating data in a file C

查看:150
本文介绍了区分文件中的数据C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取分为两种不同类型的文件的内容。如下所示:

I am trying to read the contents of a file which are sectioned into two separate types. This is shown below:

# Type names
bird
mammal
reptile
.
# Type effectiveness
Very_effective
Not_effective
.

到目前为止,我可以阅读第一个类型的内容,但是当我尝试阅读第二,我不断重读第一个内容。

So far I can read the contents of the first type, but when I try to read the contents of the second, I keep re-reading the contents of the first.

#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 hash[10];

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

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

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

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

    fclose(file);

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

当我尝试打印出第一个效果类型时,它打印出鸟等。

At the moment when I try to print out the first effectiveness type, it prints out 'bird' etc.

我觉得我很亲近,但我不知道如何处理。

I feel like I am close but I'm not sure as to how to procede.

推荐答案

问题出在你使用的方式 strtok() 。从联机帮助页:

The problem is in the way you are using strtok(). From the manpage:


strtok()函数将一个字符串解析成令牌序列。在第一次调用strtok()时,要在str中指定要解析的字符串。在每个随后的调用中,应该解析相同的字符串,str应为NULL。

The strtok() function parses a string into a sequence of tokens. On the first call to strtok() the string to be parsed should be specified in str. In each subsequent call that should parse the same string, str should be NULL.

这意味着要解析 str ,您必须首先将其称为 strtok(str,),为了进一步解析字符串,您必须将其称为 strtok(NULL,)。当您第二次将其称为 strtok(str,)时,它将从 str

That means to parse str, you have to first call it as strtok(str, " "), and to further parse the string, you have to call it as strtok(NULL, " "). When you call it as strtok(str, " ") the second time, it starts again from the beginning of str.

这篇关于区分文件中的数据C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆