I have a file(both .dat and .txt format) which contains numbers(integers) in rows and columns form. I need to read
numbers(integers) from this file. That data is to be stored in a 2D-array. This array is defined in my C program.
I have tried to use file handling in C to accomplish this, but it is not reading the whole file.
The program stops abruptly at some data in the file and exits the program.
Following is my C code used for this :
#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");
}
}
Thanks Guys for the response, But the issue is something else..
allocated the memory for the 2-d array using the following code:
#define ROW 512
#define CLMN 512
for(i = 0; i < ROW; i++)
{
for(j = 0; j < CLMN; j++)
{
array[i][j] = 0;
}
}
Also I modified the permission to ‘r’ in the following code.
homer = fopen(" homer_matrix.txt" , "r");
Still, however, I am not able to get the 2-D entries into my variable ‘array’.
p.s. The “homer_matrix.txt” is generated using matlab through following commands:
CODE:
A=imread('homer.jpg');
I=rgb2gray(A);
dlmwrite('homer_matrix.txt',I);
This code will generate the file ‘homer_matrix.txt’ which contains the grayscale values of the image in a 768 X 1024 entry form.
The following code will work for you.
It will calculate exactly how many rows and columns you have in your text file.