如何使cout表现为二进制模式? [英] How to make cout behave as in binary mode?

查看:319
本文介绍了如何使cout表现为二进制模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次我做'cout<< endl'或甚至'cout' \ n'然后启动我的程序在Windows下输出到一个文件(a.exe< test.in> result.out)我得到\r\\\
行结尾在结果。出。

Every time I do 'cout << endl' or even 'cout << "\n"' and then launch my program under Windows to output to a file ("a.exe < test.in > result.out") I get "\r\n" line endings in "result.out".

在地球上有一种方法来阻止它这样做,只是输出\\\
在每个cout< \ n'?

Is there on earth a way to stop it doing so and just output "\n" on every 'cout << "\n"'?

提前感谢。

推荐答案

我不相信你可以强制 std :: cout 输出二进制数据。用户通过C ++可以使用的最低级别接口是 streambuf std :: cout.rdbuf()。你可以很好地假设对象是 basic_filebuf 类型,并且C ++ 11标准的§27.9.1.4部分要求 basic_filebuf 实现单独的文本和二进制模式。

I don't believe you can force std::cout to output binary data. The lowest-level interface available to the user through C++ is the streambuf at std::cout.rdbuf(). You can pretty well assume that object is of type basic_filebuf, and section §27.9.1.4 of the C++11 standard requires that basic_filebuf implement separate text and binary modes.

检查您的平台特定扩展,以打开另一个流 stdout 使用其文件描述符。然后你可以在模式标志中指定 std :: binary

Check your platform-specific extensions for a way to open another stream to stdout using its file descriptor. Then you can specify std::binary in the mode flags.

但是,通过第二个转换行尾的程序。

However, it's probably easier to pipe the output through a second program that converts the line endings.

编辑:现在我看到你可能会愿意进一步真正做程序直接输出你想要的。

Now I see that you might be willing to go a little further to truly make the program directly output what you want.

只要C ++接口设置为非缓冲模式,就可以使用C接口输出换行符。

You can use the C interface to output newlines as long as the C++ interface is set to unbuffered mode.

在您的程序开始时, cout 接收任何输出之前,请执行以下操作:

At the very beginning of your program, before cout receives any output, do this:

std::cout.rdbuf()->pubsetbuf( 0, 0 ); // go to unbuffered mode

当要输出换行符时, p>

When you want to output a newline, do it like so:

_write( STDOUT_FILENO, 1, "\n" ); // do not convert line ending

你可以包装这个小... nugget ...自定义操纵: / p>

You can wrap this little… nugget… inside a custom manipulator:

#include <unistd.h>

std::ostream &endln( std::ostream &s ) {
    if ( s->rdbuf() == std::cout.rdbuf() ) { // this is cout or cerr into cout
        _write( STDOUT_FILENO, 1, "\n" ); // do not convert line ending
        return s; // stream is unbuffered, no need to flush
    } else {
        return std::endl( s ); // other streams do convert to \r\n
    }
}

这篇关于如何使cout表现为二进制模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆