简体   繁体   English

来自ReadFile()的乱码?

[英]Gibberish from ReadFile()?

I have redirected the stdout of java.exe using pipe. 我已经使用管道重定向了java.exe的标准输出。 Now I read the output using ReadFile and char buffer: 现在,我使用ReadFile和char缓冲区读取输出:

ReadFile( childStdOUTRd, buffer, sizeof(char) * 4096, &read, NULL);

The buffer will be assigned correct data. 缓冲区将被分配正确的数据。 But if I change it to TCAHR[4096]: 但是,如果我将其更改为TCAHR [4096]:

ReadFile( childStdOUTRd, buffer, sizeof(TCHAR) * 4096, &read, NULL);

The buffer received gibberish. 缓冲区收到乱码。 Do I miss something ? 我想念什么吗?

Firstly you should check the return value of ReadFile . 首先,您应该检查ReadFile的返回值。 If it returned FALSE then the read failed and the data might be gibberish. 如果返回FALSE则读取失败,并且数据可能乱码。

Also, check the value of read . 另外,检查read的值。 It will say how many characters were read. 它会说读了多少个字符。 Don't try to work with anything in the buffer beyond the value of read bytes. 不要尝试使用缓冲区中超出read字节值的任何内容。

Next, the ReadFile function receives raw bytes, it does not interpret them. 接下来, ReadFile函数接收原始字节,它不解释它们。 If your system has TCHAR defined as a 16-bit wchar_t , then this call will read 8192 bytes from the input stream. 如果您的系统将TCHAR定义为16位wchar_t ,则此调用将从输入流中读取8192字节。 It should work correctly. 它应该可以正常工作。

You didn't say how you determined that the buffer received "gibberish". 您没有说如何确定缓冲区接收到“乱码”。 If you are trying to pretend that the buffer contains actual wchar_t s but the input stream did not contain wchar_t s then it will not make sense. 如果您试图假装该缓冲区包含实际的wchar_t但输入流不包含wchar_t那么它将毫无意义。 The solution to this is: Don't Do That. 解决方案是:不要这样做。

Finally, TCHAR has not been relevant for the last 15 years. 最后, TCHAR在过去15年中一直没有意义。 Use either char or wchar_t according to your needs. 根据需要使用charwchar_t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM