很多地方会希望将数据库、资源包等文件转为数组放在.h文件中
本章内容通过命令行将参数传递给进程,将指定文件转化为数组,保存到指定的文件中
如: 进程名称 c:/123.zip c:/1.h szlen szName
主要遇到的困难:
调用fread函数,没有读到文件尾就返回0值,具体原因,fopen打开文件有两种模式,默认应该是文本模式t,这个时候fread遇到控制字符就不往后读了。解决方法:
使用binnay mode 这样就能就没有上述问题了, 来源:https://blog.youkuaiyun.com/iamoyjj/article/details/6580978,
所以 将参数”r”改为“rb” 即FILE* h_read = fopen(StringUnicodeToAscii((LPCTSTR)strSrcFile).c_str(), “rb”);
int _tmain(int argc, _TCHAR* argv[])
{
if (argc != 5)
{
return 0;
}
CString strSrcFile(argv[1]);
FILE* h_read = fopen(StringUnicodeToAscii((LPCTSTR)strSrcFile).c_str(), "rb");
if (NULL == h_read)
{
return 0;
}
CString strDestFile(argv[2]);
FILE* h_write = fopen( StringUnicodeToAscii((LPCTSTR)strDestFile).c_str(), "w" );
if (NULL == h_write)
{
fclose( h_read );
return 0;
}
char buffer[64] = {0};
int read_count = 0;
int line_max = 0;
unsigned char byte;
fseek(h_read, 0, SEEK_END);
long lSize = ftell(h_read);
fseek(h_read, 0, SEEK_SET);
CString strLenName(argv[3]);
CString strArrayName(argv[4]);
char szHead[64] = {0};
sprintf(szHead , "static int %s = %d;\n", StringUnicodeToAscii((LPCTSTR)strLenName).c_str(), lSize );
fwrite( szHead, 1, strlen(szHead), h_write );
memset(szHead, 0, 64);
sprintf(szHead , "static const unsigned char %s[%d] = {\n", StringUnicodeToAscii((LPCTSTR)strArrayName).c_str(), lSize );
fwrite( szHead, 1, strlen(szHead), h_write );
for (int i = 0; i < lSize; i++)
{
byte = 0;
memset(buffer, 0, 64);
read_count = fread(&byte, 1, 1, h_read);
if ( read_count == 1 )
{
sprintf(buffer , "0x%02x,", byte );
fwrite( buffer, 1, strlen(buffer), h_write );
if ( line_max >= (LINE_MAX-1) )
{
line_max = 0;
fwrite( "\n", 1, strlen("\n"), h_write );
}
else
{
line_max++;
}
}
}
fwrite( "\n};", 1, strlen("\n};"), h_write );
fclose(h_read);
fclose(h_write);
return 0;
}
其中 StringUnicodeToAscii 函数主要是将Unicode 转换为string型
inline string StringUnicodeToAscii(const wstring& str)
{
int nLen = WideCharToMultiByte(CP_ACP,0,str.c_str(),-1,NULL,0,NULL,NULL);
string strAscii;
strAscii.assign(nLen - 1,0);
WideCharToMultiByte(CP_ACP,0,str.c_str(),-1,(LPSTR)strAscii.data(),nLen,NULL,NULL);
return strAscii;
}