'Writing matrix of ints to .txt

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?



Solution 1:[1]

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;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Edmund