Home > Mobile >  Writing matrix of ints to .txt
Writing matrix of ints to .txt

Time:05-07

I'm trying to write a 479x639 matrix of ints to a .txt file. Preferably each line will include one entry followed by a ,, so that I can input the data on MATLAB. I used the following code to try and write the raw data to a .txt:

FILE *f = fopen("output.txt", "w");
fwrite(output, sizeof(int), 479*639, f);    
fclose(f);

All I get is a txt with corrupted data. The rest of the program runs smoothly. Any suggestions?

CodePudding user response:

Try this out and tell me if it works

#include <stdio.h>

int main() {
    int output[479][639];

    // Add values into output 2D matrix

    FILE *f = fopen("output.txt", "w");
    for (int i = 0; i < 479; i  ) {
        for (int j = 0; j < 639; j  ) {
            fprintf(f, "%d, ", output[i][j]);  
        }
        fprintf(f, "\n");
    }  
    fclose(f);
    
    return 0;
}
  • Related