繁体   English   中英

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

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

我已经为此苦苦挣扎了好几天,但仍然找不到解决方案。

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

Full_name age weight

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

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

例如:

./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 ;
}

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM