cfilematrixfwritefclose

C (BEGINNER ) - Writing a 2D array into a file


Hello i would like to store a matrix into a file here's the code I made

void fichier_print(grid_t grille, int n){
  int i,j;
  FILE *f_solution;
  f_solution=fopen("solution.txt","wb");
  if( f_solution == NULL )
  {
     printf("Le fichier est corronpu");
     exit(1);
  }
  for (i=0; i<n; i++){
    for (j=0; j<n; j++){
      fprintf(f_solution,"%c\n",grille.data[i][j]);
    }
    printf("|\n");
  }
  printf("\n");

  fclose(f_solution);

}

Here grille.data is the matrix that i want to save in a file .

The thing is that when i run the code nothing appears no .txt ( I made sure that I was in the correct directory before saying this ) .

Is there anyone with a clue ? Thanks


Solution

  • I did a simplified guess on your structure (not looking at your comments). Assuming that your data structure is correctly initilized, then it should print correctly.

    But since on your end there is a problems getting the file you want, my guess is that grille content (or in combination with n) the data is not properly initialized.

    E.g. (the simplified version)

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct grid {
        char data[10][10];
    };
    typedef struct grid grid_t;
    
    void fichier_print(grid_t grille, int n) {
        FILE *f_solution = fopen("solution.txt", "wb");
        if (f_solution == NULL) {
            perror("fopen");
            printf("Le fichier est corronpu");
            exit(EXIT_FAILURE);
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) fprintf(f_solution, "%c\n", grille.data[i][j]);
            printf("|\n");
        }
        printf("\n");
        fclose(f_solution);
    }
    
    int main(void) {
        grid_t g;
        memset(&g, 'x', sizeof g);
        fichier_print(g, 10);
        return EXIT_SUCCESS;
    }
    

    The perror would also help in clarifying what (might) be wrong when opening/creating a file.