您的位置:首页 > 其它

二进制标准输入输出防止"\r\n"与"\n"之间自重转换

2013-12-31 19:02 344 查看
使用 std::cin.read() 从文件或者管道中读取字符时,当读到 "\r\n" 时会自动转换为 "\n",同样std::cout.write() 写"\n" 时会写成 "\r\n"。
如果以二进制模式读写文件则不会有该问题,可以采用:
std::filebuf fb;
fb.open ("test2.txt", std::ios::in | std::ios::binary);
一种更通用的方式是使用 ReadFile 和 WriteFile
HANDLE std_input_handle = ::GetStdHandle(STD_INPUT_HANDLE);
while (size > 0)
{
DWORD bytes_read = 0;
if (::ReadFile(std_input_handle, buff, size, &bytes_read, NULL))
{
size -= bytes_read;
buff += bytes_read;
}
else
{
ret = false;
break;
}
}

HANDLE std_output_handle = ::GetStdHandle(STD_OUTPUT_HANDLE);
::WriteFile(std_output_handle, buff, size, &write_size, NULL);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: