提问人:Marouane Sharry 提问时间:1/16/2022 最后编辑:Marouane Sharry 更新时间:1/16/2022 访问量:64
C (BEGINNER ) - 将 2D 数组写入文件 [已关闭]
C (BEGINNER ) - Writing a 2D array into a file [closed]
问:
您好,我想将矩阵存储到文件中,这是我制作的代码
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(在说这句话之前,我确保我在正确的目录中)。
有没有人知道?谢谢
答:
0赞
Bo R
1/16/2022
#1
我对你的结构做了一个简化的猜测(不看你的评论)。假设您的结构已正确启动,那么它应该正确打印。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
评论
0赞
Jabberwocky
1/16/2022
OP甚至没有调用该函数,所以你的答案有些毫无意义......
0赞
Bo R
1/16/2022
:-)但不完全是。
上一个:在 C 中关闭文件
评论
grid_t
fichier_print
printf("fichier_print called\n");
fichier_print