我有一个包含矩阵N乘3浮点数的文本文件。我需要读取矩阵并将数据放入动态分配的数组中。我有以下代码:
#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.我无法弄清楚原因。
答案 0 :(得分:0)
在函数$ rails dev:cache
Development mode is now being cached.
中,您读取整个文件,因此当您将文件指针传递给find_length
时,它已指向它的末尾。
您可以rewind the pointer,也可以关闭文件并重新打开以解析数据。