文号
t77935
阅读
4055
回复
1
收藏
1
将raw数据转换为字符串的C++/Win32例程
2015/11/17
IP:四川
将指定长度cb的raw数据转换为字符串,用replchr替换掉异常的0字符(默认为空格),末尾加上0字符以终止字符串。可指定吃掉eatcch个前导字符(主要用于吃掉BOM)。

MakeTextA用于ANSI/UTF-8数据,将它变换为窄字符串,最后一个参数保留。

MakeTextW用于UTF-16LE/BE数据,变换为宽字符串,最后一个参数为TRUE翻转字节序。将会忽略多余的奇数字节。
#include <windows.h>
   
LPWSTR MakeTextW(LPVOID buf, INT_PTR cb, INT_PTR eatcch = 0, WCHAR replchr = L' ', BOOL reversed = FALSE)
{
    LPWSTR str = (LPWSTR)buf;
    INT_PTR cch = cb / sizeof (WCHAR);
    for (int j = 0; j < cch - eatcch; j++)
    {
        WCHAR chr = str[j + eatcch];
        if (reversed) chr = ((USHORT)chr >> 8) | ((USHORT)chr << 8);
        if (chr == 0) chr = replchr;
        str[j] = chr;
    }
    str[cch - eatcch] = 0;
    return str;
}
   
LPSTR MakeTextA(LPVOID buf, INT_PTR cb, INT_PTR eatcch = 0, CHAR replchr = ' ', BOOL reversed = FALSE)
{
    LPSTR str = (LPSTR)buf;
    INT_PTR cch = cb / sizeof(CHAR);
    for (int j = 0; j < cch - eatcch; j++)
    {
        CHAR chr = str[j + eatcch];
        if (chr == 0) chr = replchr;
        str[j] = chr;
    }
    str[cch - eatcch] = 0;
    return str;
}
   
   
int main()
{
    HANDLE hin = GetStdHandle(STD_INPUT_HANDLE);
    HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
    DWORD count = 0;
   
    WCHAR buf[200] = L"3374\0" L"\u3500\u3700\u3500\u3800整周周\0" L"222";
    CHAR bufa[200] = "3374\0" "5758整周周\0" "222";
       
    // 31 字节 = 15 WCHARs + 1 奇数字节(忽略),开头吃一个字符,0替换为空格(默认),不转换字节序(默认)
    MakeTextW(buf, 31, 1); 
    //MakeTextW(buf, 31, 1, 0x20, TRUE); 
    WriteConsoleW(hout, buf, lstrlenW(buf), &count, NULL);
    WriteConsoleW(hout, L"\n", 1, &count, NULL);
   
    MakeTextA(bufa, 18, 1);
    WriteConsoleA(hout, bufa, lstrlenA(bufa), &count, NULL);
    WriteConsoleA(hout, "\n", 1, &count, NULL);
   
    return 0;
}</windows.h>
[ 修改于11年1个月前 - 2015/11/17 18:13:29 ]
acmilan作者
11年1个月前IP:四川
797478
1楼
这两个函数对于读取文本文件非常有用。
引用
评论
笔记
{{note.content}}
{{n.user.username}}
{{fromNow(n.toc)}} {{n.status === noteStatus.disabled ? "已屏蔽" : ""}} {{n.status === noteStatus.unknown ? "正在审核" : ""}} {{n.status === noteStatus.deleted ? '已删除' : ''}}
  • 编辑
  • 删除
  • {{n.status === 'disabled' ? "解除屏蔽" : "屏蔽" }}
我也是有底线的