如何将文本文件读入结构并与其成员进行交互?

问题描述 投票:0回答:1

几天来我一直在努力奋斗,但仍无法找到解决方案。

我的文本文件有N行,每行的格式为:

Full_name age weight

我必须读取该文件并打印出具有以下格式的查询结果:

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

E.g:

./find 30 35 60.8 70.3 order by age ascending

我的结构:

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

我认为将文件的记录读入结构是这样的,但我仍然无法找到如何做到这一点。

到目前为止这是我的代码:

#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 ;
}

请帮助我改进它并找出解决方案。

任何帮助将不胜感激,谢谢。

c data-structures file-io dynamic-memory-allocation
1个回答
0
投票

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

在这里,您为记录指针分配空间,而不是记录。要为记录分配空间,您应该说:

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

要将字符串中的信息实际存储在其中一条记录中,

r[i] = str;

不是你想要的。使用sscanf代替:

sscanf(buf, "%s %d %f", r[i].name, &(r[i].age), &(r[i].weight));
© www.soinside.com 2019 - 2024. All rights reserved.