目标
若要创建结构数组的数组,请基于文件创建维度。然后将其存储到链接列表中。
我正在读取一个格式如下的文件:
读取以下格式的文件:
name (string) country (string) age (int)
john USA 54
Sam Aus 18
ect
我不知道文件将有多少行和列,也不知道每列将是什么可变类型
因此,理论上,第一个struct数组将包含[列数]strucs,它将沿行存储每个变量(使用void指针和类型转换)(所以strucArrayCol[0]=john,structurarraycol[1]=USA ect)。
这些struc数组中的每一个都将存储到另一个struc数组中,该数组将具有[行数]元素,因此strucArray2Row[0]=strucArrayCol(包含john,USA和54)和strucArrayRow[1]将包含另一个strucArrayCol(包含sam Aus 18)。
所以现在我可以读取这个文件,找到每个列的行数、列数和变量类型。
这就是我开始有麻烦的地方,因为我不知道该怎么办
1. How to create this array within array ( I know i need to use Malloc)
2.How I would store the variables in the first array of struc, if I
wanted to store age could I just do
void *data = malloc(sizeof(int));
*((int*)data) = TEMP_AGE;
void data是StrucArrayCol中的一个struc(在本例中,如果我想存储John void的年龄,*data应该在StrucArrayCol[3]中,它在StucArrayRow[0]中,作为第一行中的第三个col)
对不起,如果这是合理的话
谢谢
最佳答案
你可以在一个链表中创建一个链表,假设有人反对任何不是链表的东西!声明两个链表节点结构,一个用于文件中的行,另一个用于每行中的列:
struct column
{
char *buf;
struct column *next;
};
struct row
{
struct column *head;
struct row *next;
};
一次读取一行文件,每行添加一个
row
节点。每一行都有自己的链接列表,它将把行解析成列。struct column* column_create(struct column* cursor, char *line)
{
struct column *node = malloc(sizeof(struct column));
node->next = 0;
node->buf = malloc(strlen(line) + 1);
strcpy(node->buf, line);
if (cursor)
cursor->next = node;
return node;
}
struct row* row_create(struct row* cursor, char *line)
{
struct row *node = malloc(sizeof(struct row));
node->next = 0;
node->head = 0;
//parse the line in to columns
struct column *col = 0;
char *token = strtok(line, " \n");
while (token)
{
col = column_create(col, token);
if (!node->head)
node->head = col;
token = strtok(NULL, " \n");
}
if (cursor)
cursor->next = node;
return node;
}
或者可以使用二维文本数组(即三维字符数组)完成此操作。或者使用字符串数组保存文件中的所有行,然后将每个行解析到列中。从那里,您可以测试每一列,看看它是否是整数。
如果不知道文件中的行数,请使用
realloc
在运行时分配所需的内存。此示例读取文件中的所有行,并将其复制到行数组中:int main()
{
FILE *f = fopen("test.txt", "r");
char **lines = 0;
int lines_size = 0;
int lines_capacity = 0;
char buf[1024];
while (fgets(buf, sizeof(buf), f))
{
int len = strlen(buf);
if (!len) continue;
if (lines_size == lines_capacity)
{
lines_capacity += 16;
lines = realloc(lines, lines_capacity * sizeof(char*));
}
lines[lines_size] = malloc(len + 1);
strcpy(lines[lines_size], buf);
lines_size++;
}
int i;
for (i = 0; i < lines_size; i++)
printf("%s", lines[i]);
printf("\n");
for (i = 0; i < lines_size; i++)
free(lines[i]);
free(lines);
return 0;
}
只要文件中的行长度不超过
1024
,这就可以工作。另外,您可以使用strtok
void parseline(char *line)
{
char copy[1024];
strcpy(copy, line);
char *token = strtok(copy, " \n");
while (token)
{
printf("[%s], ", token);
token = strtok(NULL, " \n");
}
printf("\n");
}