从txt文件读取到结构 [英] Reading from txt file into a struct

查看:85
本文介绍了从txt文件读取到结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试从txt文件读取直到分号,然后将其存储到struct内部的数组中.

Trying to read from txt file until a semicolon and will store it into a array inside struct.

struct Total
{
    char *Name;
    int *No;
}MyCities;

这是我的结构使数组指针,以便以后可以分配内存.取决于txt的内容.每行都是该结构的条目.

This is my struct made the arrays pointers so i can allocate memory later. Depending on the content of the txt. Each line is a entry for the struct.

London;15
Oslo;12
vienna;35

假设这是txt文件的内容,它将把城市名称读入MyCities.Name,将分号后的数字读入MyCities.No

Let's say this is the content of txt file, it will read the city name into MyCities.Name and the number after the semicolon into MyCities.No

    FILE *fp;
    
    char line;
    

    fp = fopen("City.txt", "r");

    for (line= getc(fp); line!= EOF; line= getc(fp)) //for getting number of lines
    {
        if (line == '\n')
            count++;
    }//this is for counting how many lines in txt

    MyCities.No = malloc( count * sizeof *MyCities.No );
    if (MyCities.No == NULL) {
        fprintf(stderr, "Malloc failed.\n");
        exit(1);
    }
    MyCities.Name = malloc( count * sizeof *MyCities.Name );
    if (MyCities.Name == NULL) {
        fprintf(stderr, "Malloc failed.\n");
        exit(1);
    }

因此,在这一点上,我不知道应该如何进行.

So at this point I have no idea how should I proceed.

推荐答案

您需要以不同的方式编写结构.请记住,整数是 int ,而字符串是 char * ,即指针本身.因此,您可能需要在一个结构中存储一个 int No 和一个 char * Name ,并存储一个此类结构的数组(可以存储单独的数字数组[ int * ]和名称[ char ** ],就像您尝试过的一样,但我不建议这样做.)

You need to write your struct differently. Remember that an integer is int, yet a string is char *, i.e. a pointer itself. So you probably need to store an int No and a char* Name in a struct, and store an array of such structs (it is possible to store separate arrays of numbers [int*] and names [char**] like you tried but I’d not recommend that).

现在,假设您走了正确的路,并且拥有一个结构 City ,其中包含一个数字和一个字符串字段,就像您知道的行数一样(有一些方法可以避免这种通过,但是它们更复杂),您可以继续并分配 City 的数组,例如使用 calloc(count,sizeof(City))(它可以进行乘法运算,也可以对数组进行零填充).

Now, assuming you went the right way and have a struct City with a number and a string fields inside, as you know line count (there are ways to avoid that pass but they are more complicated) you may proceed and allocate an array of City, e.g. using calloc(count, sizeof(City)) (it does the multiplication, and also zero-fills the array).

现在您可以再次读取文件(不要忘记倒带或重新打开),逐行显示. getdelim 应该适合阅读第一个字段,并且

Now you can read the file again (don’t forget to rewind or reopen it), line by line. getdelim should be suitable to read the first field, and fscanf is good for everything else.

这篇关于从txt文件读取到结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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