我有一个包含数字(整数)的行和列形式的文件(包括.dat和.txt格式)。我需要从这个文件中读取 数字(整数)。该数据将被存储在二维数组中。这个数组是在我的C程序中定义的。 我试图在C中使用文件处理来实现这一点,但它并没有读取整个文件。 程序突然停止在文件中的某些数据并退出程序。 以下是用于此我的C代码:从文件中读取数字(整数)并将其存储为二维数组
#define ROW 512
#define CLMN 512
for(i = 0; i < ROW; i++)
{
for(j = 0; j < CLMN; j++)
{
array[i][j] = 0;
}
}
:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define EOL '\n'
int main(){
int i = 0,j = 0,array[][]; //i is row and j is column variable, array is the target 2d matrix
FILE *homer;
int v;
homer = fopen("homer_matrix.dat","w"); //opening a file named "homer_matrix.dat"
for(i=0;;i++)
{
for(j=0;;j++)
{
while (fscanf(homer, "%d", &v) == 1) //scanning for a readable value in the file
{
if(v==EOL) //if End of line occurs , increment the row variable
break;
array[i][j] = v; //saving the integer value in the 2d array defined
}
if(v==EOF)
break; //if end of file occurs , end the reading operation.
}
}
fclose(homer); //close the opened file
for(i=0;i<=1000;i++)
{
for(j=0;j<=1200;j++)
printf(" %d",array[i][j]); //printing the values read in the matrix.
printf("\n");
}
}
谢谢你们的反应,但问题是别的东西.. 使用下面的代码分配给2-d阵列的存储
另外,我在下面的代码中修改了'r'的权限。
homer = fopen(" homer_matrix.txt" , "r");
但是,我仍然无法将2-D条目放入我的变量'数组'中。
p.s.所述“homer_matrix.txt”是使用MATLAB生成通过以下命令:
CODE:
A=imread('homer.jpg');
I=rgb2gray(A);
dlmwrite('homer_matrix.txt',I);
此代码将生成的文件“homer_matrix.txt”包含在768 X中的图像的灰度值1024条目表单。
谢谢,我刚才我的编辑与编辑的代码的问题,这将是巨大的,如果你能帮助 –
@JimmyThakkar如何是你的阵列'array'现正在申报?请显示你的数组的声明。 – ouah
的#define ROW 234 的#define CLMN 327 INT主(无效) { INT I = 0,J = 0,阵列[ROW] [CLMN]; // i是行,j是列变量,array是目标2d //矩阵 –