C语言 将二维数组写入C中的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4638568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
write 2d array to a file in C
提问by Bobj-C
I used to use the code below to Write an 1D array to a File:
我曾经使用下面的代码将一维数组写入文件:
FILE *fp;
float floatValue[5] = { 1.1F, 2.2F, 3.3F, 4.4F, 5.5F };
int i;
if((fp=fopen("test", "wb"))==NULL) {
printf("Cannot open file.\n");
}
if(fwrite(floatValue, sizeof(float), 5, fp) != 5)
printf("File write error.");
fclose(fp);
/* read the values */
if((fp=fopen("test", "rb"))==NULL) {
printf("Cannot open file.\n");
}
if(fread(floatValue, sizeof(float), 5, fp) != 5) {
if(feof(fp))
printf("Premature end of file.");
else
printf("File read error.");
}
fclose(fp);
for(i=0; i<5; i++)
printf("%f ", floatValue[i]);
My question is if i want to write and read 2D array ??
我的问题是我是否想写入和读取二维数组?
回答by 6502
You can use the same approach... just make the following changes
您可以使用相同的方法...只需进行以下更改
float floatValue[3][5] = {{ 1.1F, 2.2F, 3.3F, 4.4F, 5.5F },
{ 6.6F, 7.7F, 8.8F, 9.9F, 8.8F },
{ 7.7F, 6.6F, 5.5F, 4.4F, 3.3F }};
int i,j;
...
...
if(fwrite(floatValue, sizeof(float), 3*5, fp) != 3*5)
...
...
if(fread(floatValue, sizeof(float), 3*5, fp) != 3*5) {
...
...
for(j=0; j<3; j++) {
for(i=0; i<5; i++)
printf("%f ", floatValue[j][i]);
printf("\n");
}
Note of course that this is not the best way to save/load data especially if you want to have some compatibility between different compilers/systems or even just with the future.
The topic of saving and restoring is often named serializationand with just a very small minor overhead you can get much more flexibilty especially once the data model becomes more complex.
当然请注意,这不是保存/加载数据的最佳方式,特别是如果您希望在不同的编译器/系统之间具有某种兼容性,甚至只是与未来兼容。保存和恢复的主题经常被命名serialization,只需很小的开销,您就可以获得更大的灵活性,尤其是在数据模型变得更加复杂时。
回答by Iraklis
Instead of a single for loop you will add an other one e.g.:
您将添加另一个循环,而不是单个 for 循环,例如:
for(i=0;i<lines;i++) {
for(j=0;j<num;j++) {
fprintf(file,"%d ",array[i][j]);
}
fprintf(file,"\n");}

