作者:朱金灿
来源:clever101的专栏
为什么大多数人学不会人工智能编程?>>>
最近面临这样一个需求:以比较节省存储空间的存储一组坐标点到文件,要求程序能够跨平台读写这种文件。思考了一下,比较简单的方式是以二进制文件的方式保存,先存入点的个数,然后把点结构体逐个存储进去。因为要节省存储空间,得保证结构体是以单字节对齐的。代码如下:
#include <stdio.h>
#include <string>
#include <vector>/* 对齐结构成员到1字节 */
#ifdef __GNUC__
#define GNUC_PACKED __attribute__((packed))
#else
#define GNUC_PACKED
#endif
#ifdef __arm
#define ARM_PACKED __packed
#else
#define ARM_PACKED
#endif
#if defined(_WIN32) || defined(_WIN64)
#pragma pack(1)
#endif
ARM_PACKED/*
坐标点结构体
*/
struct stPointCoodinate
{double m_CoodinateX; //x坐标double m_CoodinateY; //y坐标
};#if defined(_WIN32) || defined(_WIN64)
#pragma pack()
#endif/*
将点结构体转化为二进制文件
具体是先写入点的数目,然后再逐个写入点
*/
int WritePointsToFile(const std::vector<stPointCoodinate>& vecTarget, const std::string& binFile)
{if (vecTarget.empty()){printf("point number is 0\n");return -1;}FILE* fp = fopen(binFile.c_str(), "wb");if (NULL == fp){printf("create point file failed!\n");return -2;}int nTargetNum = vecTarget.size();fwrite(&nTargetNum, sizeof(int), 1, fp);fwrite(&vecTarget[0], sizeof(stPointCoodinate), nTargetNum, fp);fclose(fp);return 0;
}/*
从文件中读入点数据
*/
int ReadPointsFromFile(const std::string& binFile, std::vector<stPointCoodinate>& vecTarget)
{FILE* fp = fopen(binFile.c_str(), "rb");if (NULL == fp){printf("point file open failed!\n");return -1;}int nTargetNum = 0;fread(&nTargetNum, sizeof(int), 1, fp);vecTarget.resize(nTargetNum);fread(&vecTarget[0], sizeof(stPointCoodinate), nTargetNum, fp);fclose(fp);return 0;
}/*
测试点文件的读写
*/
void TestPointFileRW()
{std::vector<stPointCoodinate> vecTarget;for (int i = 0; i < 5; i++){stPointCoodinate pt;pt.m_CoodinateX = 100.0 + i * 10.0;pt.m_CoodinateY = 100.0 + i * 10.0;vecTarget.push_back(pt);}#if defined(_WIN32) || defined(_WIN64)std::string binFile = "D:\\TestData\\test_point.pt";#elsestd::string binFile = "/home/lx/TestData/test_point.pt";#endifint ret = WritePointsToFile(vecTarget, binFile);vecTarget.clear();ret = ReadPointsFromFile(binFile, vecTarget);if (!vecTarget.empty()){int num = vecTarget.size();for (int i = 0; i < num; i++){printf("%f,%f \n", vecTarget[i].m_CoodinateX, vecTarget[i].m_CoodinateY);}}
}int main(int argc, char* argv[])
{TestPointFileRW();getchar();return 0;
}
windows效果图如下:
linux效果图如下: