Ankit Kulshrestha Ankit Kulshrestha - 19 days ago 6
C Question

Reading in different rows of a 2d array in a single buffer using fread

I'm trying to read a file which has got a matrix stored on it. In my source file, I've got a buffer which has the size

rows*cols
. The matrix is stored in row major order. I want to use
fread
to read in the rows of the matrices in this fashion :

buf[0..row-1] = first row

buf[row .. 2row-1] = second row

and so on. Is it possible to use
fread
to do this? If not what other alternatives are there?

So here's what I've written in terms of code:

for(k = 0; k<row*cols;k++)
{
fread(buf,sizeof(double), row*cols*k,&fp);

}


However, as I mentioned in the pseudocode above, I want
buf[0..row-1]
to contain row 0,
buf[row..2row-1]
to contain row 2 and so on.

Answer

sample code

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>

int main(void){
    int rows = 4, cols = 3;
    double matrix[rows][cols];
    double buf[rows*cols];
    assert(sizeof(matrix) == rows*cols*sizeof(double));

    srand(time(NULL));
    //make matrix
    puts("original matrix");
    for(int r = 0; r < rows; ++r){
        for(int c = 0; c < cols; ++c){
            matrix[r][c] = (double)rand()/RAND_MAX;
            printf("%f ", matrix[r][c]);
        }
        puts("");
    }

    //write file
    FILE *fp = fopen("data.dat", "wb");
    fwrite(matrix, sizeof(matrix), 1, fp);
    fclose(fp);

    //read file to 1D buf
    fp = fopen("data.dat", "rb");
    fread(buf, sizeof(double), rows*cols, fp);
    fclose(fp);

    puts("\nread matrix as 1D");
    for(int r = 0; r < rows; ++r){
        for(int c = 0; c < cols; ++c){
            printf("%f ", buf[r * cols + c]);
        }
        puts("");
    }

    double buf_of_one_row[cols];
    //read file each row
    fp = fopen("data.dat", "rb");
    puts("\nread matrix as 1D each row");
    for(int r = 0; r < rows; ++r){
        fread(buf_of_one_row, sizeof(double), cols, fp);
        for(int c = 0; c < cols; ++c){
            printf("%f ", buf_of_one_row[c]);
        }
        puts("");
    }
    fclose(fp);
}
Comments