c语言-DEM二进制文件读写
程序员文章站
2022-07-15 08:12:18
...
文章目录
c语言-DEM二进制文件读写
网上的好多程序都太复杂了,查来查去都和结构体读写有关系。
目标:通过编程实现一种简单的.dat格式,二进制存储(写)、二进制读取(读)文件的程序,文件保存的是地理信息的DEM融合数据。
优势:数据写到文件效率最高的方法是用二进制形式写入。二进制输出避免了再数值转换字符串过程中涉及的开销和精度损失。但是二进制数据并非人眼所能阅读。
环境
- Windows 10
- Visual studio 2017
代码要点
- C语言-二进制文件读写流,fopen-fwrite-fclose,fopen-fread-fclose;
- C语言数据格式、占用内存长度;
- 数组长度(总长度)的计算;
参考代码
/**DEM_Result.dat File Reader*/
/**by Dr.Zheng*/
/**libs*/
# include<stdio.h>
# include<stdlib.h>
/**File Pointers*/
FILE *fpin, *fpout;
void main(void)
{
int ch, i, ch1, data[100], data_out[100] = { 0 };
/**New a dataset*/
/*sizeof可以获得数据类型或变量在内存中所占的字节数,也可以获得整个数组在内存中所占的字节数*/
for (i = 0; i < sizeof(data)/sizeof(int); i++)
{
data[i] = i;
}
/* When use "fopen_s " the errno_t type is necessary*/
errno_t err;
/* Open for read (will fail if file "data" does not exist) */
if ((err = fopen_s(&fpin, "DEM_ResultSaveTest.dat", "wb")) != NULL)
exit(0);
/*写二进制文件fwrite save data in binary format*/
//fwrite(&data[0], sizeof(int), 1, fpin);
for (int k = 0; k < sizeof(data)/sizeof(int); k++)
{
if (fwrite(&data[k], sizeof(int), 1, fpin) != 1)
{
printf("file write error!\n");
}
}
/* Close fpin */
if (fpin)
{
if (fclose(fpin))
printf("The file 'DEM_ResultSaveTest.dat' was not closed\n");
}
printf("The file 'DEM_ResultSaveTest.dat' was closed\n");
/*读二进制文件*/
/* Open for read (will fail if file "data" does not exist) */
if ((err = fopen_s(&fpout, "DEM_ResultSaveTest.dat", "rb")) != NULL)
exit(0);
/*fwrite save data in binary format*/
for (int j = 0; j < 100; j++)
{
fread(&data_out[j], sizeof(int), 1, fpout);
}
/* Close fpin */
if (fpout)
{
if (fclose(fpout))
printf("The file 'DEM_ResultSaveTest.dat' was not closed\n");
}
printf("The file 'DEM_ResultSaveTest.dat' was closed\n");
system("pause");
}
结果验证
在system(‘pause’)设置断点,然后以调试模式运行程序,查看局部变量,如下图所示,data为写入数据,data_out为读入数据,两者一致。