Reading from txt file into a struct

本秂侑毒 提交于 2021-02-11 14:29:35

问题


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;

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

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.


回答1:


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).

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).

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.



来源:https://stackoverflow.com/questions/64652352/reading-from-txt-file-into-a-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!