C(初学者)- 将二维数组写入文件

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

你好,我想将矩阵存储到文件中,这是我编写的代码

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

}

这里grille.data是我要保存在文件中的矩阵

问题是,当我 运行 代码没有出现时,没有 .txt (在说这句话之前,我确保我在正确的目录中)。

有人知道吗?谢谢

我对你的结构做了一个简单的猜测(没有看你的评论)。假设您的 data 结构已正确初始化,那么它应该会正确打印。

但是由于您在获取所需文件时遇到问题,我的猜测是 grille 内容(或与 n 结合使用)数据未正确初始化。

例如(简化版)

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

perror 也有助于阐明 opening/creating 文件时(可能)出现的错误。