将二维数组写入C中的文件
我曾经使用下面的代码将一维数组写入文件:
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]);
我的问题是我是否想写入和读取二维数组?
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 ??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用相同的方法...只需进行以下更改
...
...
...
当然请注意,这不是保存/加载数据的最佳方法,特别是如果您想在不同编译器之间具有一定的兼容性/系统,甚至只是未来。
保存和恢复的主题通常被称为“序列化”,只需很小的开销,您就可以获得更大的灵活性,特别是当数据模型变得更加复杂时。
You can use the same approach... just make the following changes
...
...
...
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
serialization
and with just a very small minor overhead you can get much more flexibilty especially once the data model becomes more complex.您将添加另一个 for 循环,而不是单个 for 循环,例如:
Instead of a single for loop you will add an other one e.g.: