今天遇到一个问题,需要用到一些.dat文件,每个文件大概300字节,是一些系统配置数据。考虑到用到的地方比较多,每次读一次性能也不好,便考虑将.dat文件存为字节数组,作为全局配置数据,这样就比较方便。接下来找了下直接转换的方法,似乎是没有合适的。所以就打算自己写一个,便于处理,不然自己一个个的输入就太煎熬了。
基本的做法是先读取.dat文件,再将按字节数组的方式处理,这里将其保存为txt文件的形式。
#include <iostream>
#include <fstream>
#include <sstream>
#include <fcntl.h>
#include <iomanip>
#include <string>
std::string num2HexString(int value)
{
std::ostringstream ss;
ss<<std::hex<<value;
std::string tmp_str = "0x";
tmp_str += ss.str();
std::cout.clear();
std::cout<<std::dec;
return tmp_str;
}
int main()
{
std::ifstream infile("9.dat",std::ios::binary);
std::ofstream outfile("9.txt");
unsigned char ch;
int count = 0;
while(!infile.eof())
{
ch = infile.get();
outfile<<num2HexString(ch);
outfile<<",";
}
infile.close();
outfile.close();
getchar();
return 0;
}
将输出的txt文件导成字节数据就ok了。