如何将字符串数组 fwrite 和 fread 写入文件?
How do I fwrite and fread array of strings to file?
我想将一个字符串数组写入一个文件。现在,我首先写入数组中的字符串数,然后使用以下代码写入数组:
int rows = 3;
char **c = calloc (rows,sizeof(char*));
c[0] = "cat[=10=]";
c[1] = "dog[=10=]";
c[2] = "mouse[=10=]";
FILE * f = fopen("test", "w");
if (f) {
fwrite(&rows, sizeof(int), 1, f);
fwrite(c, sizeof(char*), rows, f);
}
fclose(f);
当我读回数据时,我得到一个空字符**。这是我的代码:
FILE * f = fopen("test", "r");
if (f) {
int num = -99;
fread(&num, sizeof(int), 1, f);
char** buff = malloc(num*sizeof(char*));
fread(buff, sizeof(char), num, f);
buff[num] = 0x00;
for(int i = 0; i < num; i++) {
printf("%s ", buff[i]);
}
printf("\n");
}
您只需将变量 c
的地址写入文件“test
”(通过函数 fwrite(c,sizeof...)
)。你为什么不把值写入文件?
我想将一个字符串数组写入一个文件。现在,我首先写入数组中的字符串数,然后使用以下代码写入数组:
int rows = 3;
char **c = calloc (rows,sizeof(char*));
c[0] = "cat[=10=]";
c[1] = "dog[=10=]";
c[2] = "mouse[=10=]";
FILE * f = fopen("test", "w");
if (f) {
fwrite(&rows, sizeof(int), 1, f);
fwrite(c, sizeof(char*), rows, f);
}
fclose(f);
当我读回数据时,我得到一个空字符**。这是我的代码:
FILE * f = fopen("test", "r");
if (f) {
int num = -99;
fread(&num, sizeof(int), 1, f);
char** buff = malloc(num*sizeof(char*));
fread(buff, sizeof(char), num, f);
buff[num] = 0x00;
for(int i = 0; i < num; i++) {
printf("%s ", buff[i]);
}
printf("\n");
}
您只需将变量 c
的地址写入文件“test
”(通过函数 fwrite(c,sizeof...)
)。你为什么不把值写入文件?