任意文件转数组

很多地方会希望将数据库、资源包等文件转为数组放在.h文件中
本章内容通过命令行将参数传递给进程,将指定文件转化为数组,保存到指定的文件中
如: 进程名称 c:/123.zip c:/1.h szlen szName

主要遇到的困难:
  调用fread函数,没有读到文件尾就返回0值,具体原因,fopen打开文件有两种模式,默认应该是文本模式t,这个时候fread遇到控制字符就不往后读了。解决方法:
使用binnay mode 这样就能就没有上述问题了, 来源:https://blog.csdn.net/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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值