I searched here, but nothing of what I found seems to work for me. I'm working on a project and I'm trying to implement a function which heading is the following:
read_from_file(*r, *col, fp);
\param *r, where the number of rows of the new matrix is going to be stored; \param *col where the number of columns of the new matrix is going to be stored; \param fp the file, already opened in reading mode in the main of the program, where to read from the matrix.
\retval must p, pointer to the new matrix, read from file.
Now, each file is something like:
..........
.......@..
.....@@@@.
.....@@@..
..........
..........
..........
..........
..........
..........
Basically the program must have the option of uploading a sedimentation area, made of empty cells, the '.', and in case obstacles, the '@'. Some cells can also be full, '*'. Those "special characters" are also defined like this:
#define EMPTY '.'
#define FULL '*'
#define OBSTACLE '@'
The matrix representing the sedimentation area must be a 2D dynamically allocated array. I wrote the piece of code about the evaluation of the number of rows and columns and it works just fine. I'm having issue trying to do the following: in the example file I wrote here, the matrix is a 10x10 one, so, one allocated enough space for the matrix:
char**p = malloc(row*sizeof(char*));
int i = 0;
for(i = 0; i < row; i++){
p[i] = malloc(columns*sizeof(char));
What I'm trying to accomplish reading from file is:
p[1][1] = '.';
p[1][2] = '.';
....
p[2][8] = '@';
And so on. I've tried in many ways, but nothing seems to work. Once i try to write this new matrix on file, when I'm trying to read the output, there is an error message display which says that the file is corrupted. Can anybody help me?
I tried like this:
char*buffer = malloc(sizeof(char));
int k;
while(fgets(buffer, columns, fp) != NULL){
for(i = 0; i < row; i++){
k = 0;
for(j = 0; j < columns; j++){
if(j == col-1)
p[i][j] = buffer[columns - 1]; /* excluding ‘\0’ here */
else
p[i][j] = buffer[k++];
}
}
}
I even tried like this:
While((c = fgetc(fp))) != EOF){
for(i = 0; i < row; i++){
for(j=0; j< columns; j++){
p[i][j] = c;
}
}
}
Thanks in advance.