我已经为此苦苦挣扎了好几天,但仍然找不到解决方案。
我的文本文件有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 ;
}
请帮助我进行改进并找出解决方案。
谢谢您的任何帮助。
答案 0 :(得分: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));