2012-08-26 120 views
1

我有一个包含数字(整数)的行和列形式的文件(包括.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条目表单。

回答

1

以下代码适用于您。 它会计算你的文本文件中有多少行和列。

do { //calculating the no. of rows and columns in the text file 
    c = getc (fp); 

    if((temp != 2) && (c == ' ' || c == '\n')) 
    { 
     n++; 
    } 
    if(c == '\n') 
    { 
     temp =2; 
     m++; 
    } 
} while (c != EOF); 
fclose(fp); 
2
int i = 0,j = 0,array[][]; 

这里的array声明无效。

+0

谢谢,我刚才我的编辑与编辑的代码的问题,这将是巨大的,如果你能帮助 –

+0

@JimmyThakkar如何是你的阵列'array'现正在申报?请显示你的数组的声明。 – ouah

+0

的#define ROW 234 的#define CLMN 327 INT主(无效) { INT I = 0,J = 0,阵列[ROW] [CLMN]; // i是行,j是列变量,array是目标2d //矩阵 –

0

你忘了你的阵列

int i = 0,j = 0,array[][]; 

分配内存,这应该是这样的

#define MAXCOLS 1000 
#define MAXROWS 1000 
int i = 0,j = 0,array[MAXROWS][MAXCOLS]; 
1
homer = fopen("homer_matrix.dat","w"); 

这不是好主意,打开文本文件与标志“W”阅读。尝试使用“rt”代替。

+0

编辑代码,如果您有任何其他解决方案,请查看它,谢谢 –

+0

请将您的文本文件的几行添加到您的问题或与Dropbox共享整个文件。com或者其他什么,我会根据你的数据尝试修复你的代码。顺便说一句,你确定导出和解析文本文件对你有好处吗?我认为如果你在matlab中导出二进制文件,然后在C程序中将它读入内存将会更好。 – Tutankhamen

+0

感谢您的帮助,我找到了解决办法。 –

相关问题