[英]Reading a text file into a two dimentional array in C
I have a text file that looks like the following.我有一个如下所示的文本文件。
5
2 7
3 4 2
Basically, row 1 has 1 element, row 2 has 2 elements, row 3 has 3 elements, ... up to n rows with n elements.基本上,第 1 行有 1 个元素,第 2 行有 2 个元素,第 3 行有 3 个元素,......最多 n 行有 n 个元素。
I need to read them, and put into a 2-d array in this fashion:我需要阅读它们,并以这种方式放入一个二维数组:
a[0][0] = 5
a[1][0] = 2
a[1][1] = 7
a[2][0] = 3
a[2][1] = 4
a[2][2] = 2
...
You get the drift.你得到了漂移。
However I know n (the number of rows) only at run time.但是我只在运行时知道 n (行数)。 How would I go about reading the file into a 2x2 array?
我将如何将文件读入 2x2 数组?
I know I can do the following if I know the number of elements in each line of text, and if that number is the same for each line.我知道如果我知道每行文本中的元素数量,并且每行的元素数量相同,我可以执行以下操作。
fa = fopen("file.txt", "r");
for(i = 0; i < n; i++) {
fgets(str, 1000, fa);
sscanf(str, "%d %d %d", &a[i][0], &a[i][1], &a[i][2]);
}
fclose(fa);
But it wouldn't help me here as I have varying number of elements in each row.但这对我没有帮助,因为每行中有不同数量的元素。
How do I go about this?我该怎么做?
Allocate memory for the array like this:像这样为数组分配内存:
int** array;
array = malloc(n * sizeof(*array)); /* Assuming `n` is the number of rows */
if(!array) /* If `malloc` failed */
{
fputs(stderr, "Error allocating memory; Bailing out!");
exit(-1);
}
int count = 1;
for(int i = 0; i < n; i++)
{
array[i] = malloc(count * sizeof(**array));
if(!array[i]) /* If `malloc` failed */
{
for(int j = 0; j < i; j++) /* free previously allocated memory */
{
free(array[j]);
}
free(array);
fputs(stderr, "Error allocating memory; Bailing out!");
exit(-1);
}
count++;
}
Then, read data from the file into the array by using:然后,使用以下命令将文件中的数据读入数组:
FILE* fp = fopen("file.txt", "r");
if(!fp)
{
for(int i = 0; i < n; i++) /* free previously allocated memory */
{
free(array[i]);
}
free(array);
fputs(stderr, "Error opening 'file.txt'; Bailing out!");
exit(-1);
}
int max = 1;
for(int i = 0; i < n; i++)
{
for(count = 0; count < max; count++)
{
fscanf(fp, "%d", &array[i][count]);
}
max++;
}
Then print the results:然后打印结果:
max = 1;
for(int i = 0; i < n; i++)
{
for(count = 0; count < max; count++)
{
printf("array[%d][%d] = %d", i, count, array[i][count]);
}
max++;
}
And finally, free the allocated memory:最后,释放分配的内存:
for(int i = 0; i < n; i++)
{
free(array[i]);
}
free(array);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.