我有一个文本文件,该文件包含3个浮点数的矩阵N。我需要读取矩阵并将数据放入动态分配的数组中。我有以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define X_ 0
#define Y_ 0
#define Z_ 0
#define VERTEX_COUNT 3
void read_data(FILE* FILE_POINTER, float **GRID, int N_LINES)
{
int i = 0, j=0;
for(i = 0; i < N_LINES; i++)
{
for(j = 0; j < VERTEX_COUNT; j++)
{
if (!fscanf(FILE_POINTER, "%f", &GRID[i][j]))
break;
}
}
}
int find_length(FILE* FILE_POINTER)
{
int ch = 0;
int length = 0;
if(FILE_POINTER != NULL)
{
while(!feof(FILE_POINTER))
{
ch = fgetc(FILE_POINTER);
if(ch == '\n')
{
length++;
}
}
}
else
{
perror("File not found");
exit(EXIT_FAILURE);
}
return length;
}
int main()
{
/* Define variables needed*/
int i=0,j=0;
float** GRID_GEOM;
float** GRID_TOPO;
/* Open the files containing the data*/
FILE* FILE_GEOM = fopen("temporary_geom.txt","r");
FILE* FILE_TOPO = fopen("temporary_topo.txt","r");
/* Find length of the data set*/
int N_POINTS = find_length(FILE_GEOM);
int N_TRIANG = find_length(FILE_TOPO);
/* Dynamically allocate memory for each data set*/
GRID_GEOM = malloc(N_POINTS * sizeof(float*));
for (i = 0; i < N_POINTS; i++)
{
GRID_GEOM[i] = malloc(VERTEX_COUNT * sizeof(float));
}
GRID_TOPO = malloc(N_TRIANG * sizeof(float*));
for (i = 0; i < N_TRIANG; i++)
{
GRID_TOPO[i] = malloc(VERTEX_COUNT * sizeof(float));
}
/* Read data into the arrays*/
read_data(FILE_GEOM, GRID_GEOM, N_POINTS);
/* Close the files */
fclose(FILE_GEOM);
fclose(FILE_TOPO);
/* Free the memory allocated */
for (i = 0; i < N_POINTS; i++)
{
free(GRID_GEOM[i]);
}
free(GRID_GEOM);
for (i = 0; i < N_TRIANG; i++)
{
free(GRID_TOPO[i]);
}
free(GRID_TOPO);
}
当我尝试访问GRID_GEOM矩阵中的任何位置时,所有值似乎都是0。我不知道为什么。
最佳答案
在功能find_length
中,您将读取整个文件,因此,当您将文件指针传递给read_data
时,它已经指向文件的末尾。
您可以rewind the pointer或关闭文件,然后再次重新打开它以分析数据。
关于c - 读写动态分配的数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41968331/