How can I read a text file into a structure and interact with its members?

I've been struggling with this for days and still can't find its solution.

My text file has N lines and each line of it has the format of:

Full_name age weight

I have to read that file and print out the result of a query which has the format:

./find age_range weight_range order by [age/weight] [ascending/descending]

E.g:

./find 30 35 60.8 70.3 order by age ascending

My structure:

Struct record{
char name[20];
  int age;
  float weight;
};

I think reading the file's records into structure is the case but I still can't find out how to do it.

This is my code so far:

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

const int STEPSIZE = 100;

struct record {
    char name[20];
  int age;
  float weight;
};

void ** loadfile(char *filename, int *len);
int main(int argc, char *argv[])
{
    if(argc == 1)
    {
        printf("Must supply a filename to read\n");
        exit(1);
    }

    int length = 0;
     loadfile(argv[1], &length);

}

void ** loadfile(char *filename, int *len)
{
    FILE *f = fopen(filename, "r");
    if (!f)
    {
    printf("Cannot open %s for reading\n", filename);
    return NULL;
    }

    int arrlen = STEPSIZE;

    //Allocate space for 100 char*
    struct record **r = (struct record**)malloc(arrlen * sizeof(struct record*));


    char buf[1000];
    int i = 0;
    while(fgets(buf, 1000, f))
    {
        //Check if array is full, If so, extend it
        if(i == arrlen)
        {
        arrlen += STEPSIZE;

        char ** newlines = realloc(r, arrlen * sizeof(struct record*));
        if(!newlines)
        {
            printf("Cannot realloc\n");
            exit(1);
        }
        r = (struct record**)newlines;
        }

    //Trim off newline char
    buf[strlen(buf) - 1] = '\0';

    //Get length of buf
    int slen = strlen(buf);

    //Allocate space for the string
    char *str = (char *)malloc((slen + 1) * sizeof(char));

    //Copy string from buf to str
    strcpy(str, buf);

    //Attach str to data structure
    r[i] = str;

    i++;
    }
    *len = i; //  Set the length of the array of char *
    return ;
}

Please help me to improve it and find out the solution.

Any help would be appreciated, thanks.

1 answer

  • answered 2018-09-19 05:01 user18359

    struct record **r = (struct record**)malloc(arrlen * sizeof(struct record*));

    Here, you are allocating space for pointers to records, not records. To allocate space for records you should instead say:

    struct record *r = (struct record*)malloc(arrlen * sizeof(struct record));
    

    To actually store the information from your string in one of the records,

    r[i] = str;

    is not what you want. Use sscanf instead:

    sscanf(buf, "%s %d %f", r[i].name, &(r[i].age), &(r[i].weight));