将2d数组写入C中的文件 [英] write 2d array to a file in C

查看:141
本文介绍了将2d数组写入C中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经使用下面的代码将1D数组写入文件:

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

我的问题是,如果我想写和读取2D数组?

My question is if i want to write and read 2D array ??

推荐答案

您可以使用相同的方法......只需进行以下更改

You can use the same approach... just makes 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 serialization and with just a very small minor overhead you can get much more flexibilty especially once the data model becomes more complex.

这篇关于将2d数组写入C中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆