我编写了这个函数,它打开一个管道并将命令传递到要执行的管道,在检查缓冲区时,我注意到有些命令占用 1 个字节,其他命令占用 2 个字节,据说尝试将缓冲区输出到屏幕会导致一些要输出为 Mojibake 的命令
\n#include <io.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nint test(wchar_t * command)\n{\n int i =0;\n wchar_t psBuffer[128];\n FILE *pPipe;\n\n if( (pPipe = _wpopen( command, L"rb" )) == NULL )\n exit( 1 );\n\n wchar_t c;\n while ( (c = fgetwc(pPipe)) != WEOF && i < 128)\n {\n psBuffer[i] = c;\n wprintf(L"%04X ",c);\n i++;\n }\n psBuffer[i] = L'\\0';\n wprintf(L"\\n%S", psBuffer);\n if (feof( pPipe))\n _pclose( pPipe );\n return 0;\n}\n\nint main()\n{\n _setmode(fileno(stdout), _O_U8TEXT);\n test(L"C:\\\\Windows\\\\System32\\\\cmd.exe /u /c dir /b");\n wprintf(L"\\n");\n test(L"C:\\\\Windows\\\\System32\\\\cmd.exe …Run Code Online (Sandbox Code Playgroud) 考虑以下两个函数,第一个函数使用 Windows API 函数ReadFile()和CreateFileW(),而第二个函数使用fopen()和fgetws(),从名为 的文件中读取非英语文本data.txt。
第一个函数输出垃圾文本,而第二个函数输出文件中的文本,没有任何问题。
\n请注意,fopen()hasccs=UTF-8定义了要使用的字符编码,而read_file_2()does 没有类似的内容。
DWORD read_file_2()\n{\n wchar_t wstr[512];\n BOOL success = FALSE;\n DWORD dwRead, total =0;\n HANDLE handle = CreateFileW(L"data.txt",\n GENERIC_READ,\n 0,\n NULL,\n 3,\n FILE_ATTRIBUTE_NORMAL,\n NULL);\n if (handle == INVALID_HANDLE_VALUE)\n return -1;\n do\n { \n success = ReadFile(handle, wstr, 20, &dwRead, NULL);\n total += dwRead;\n } while(!success || dwRead == 0);\n\n wstr[total] = L\'\\0\';\n wprintf(L"%ls\\n",wstr);\n return 0;\n}\n\nvoid …Run Code Online (Sandbox Code Playgroud)