[英]getting information from standard output ( C++ )?
如何从标准输出中读取以下信息?
Fmail@yasar.com \\ 0Tketo@keeto.com \\ 0Tmail@lima.com \\ 0 \\ 0
我想拥有整个信息,包括\\0
字符。
有了这样的代码:
string s;
fstream fs("/dev/stdout", fstream::in);
fs >> s;
如果我写s
到文件我得到这个输出:
Ftest555 @ itap.gov.trTislam.yasar @ inforcept.comTaa @ test.comTbb @ test.com
所有\\0
和\\0\\0
都丢失了。
我怎样才能做到这一点?
这只是在shell中正确处理输出的问题。
想象一下:
cat file_with_nulls
这将不计后地将file_with_nulls
的内容打印到控制台,当然控制台可能没有配备显示不可打印的字符。 但是,以下工作:
cat file_with_nulls > otherfile
这将创建file_with_nulls
的完美副本。
这同样适用于您的程序。 您可以将任何想要的内容写入标准输出。 但是不要指望你的终端或控制台做任何有用的事情! 相反,将输出重定向到一个文件,一切都很好:
./myprog > output.bin
请注意,C字符串操作通常不使用空字节,因此在C中您应该使用fwrite()
。 在C ++中,字符串可以包含任何字符,因此std::cout << str;
永远有效。 但是,从C字符数组构造std::string
在空字节处停止,因此您必须使用不同的构造函数:
char cstr[] = { 'H', 'e', 0, 'l', 'l', 'o', 0 };
std::string s1(cstr); // wrong, gives you "He"
std::string s2(cstr, sizeof(cstr)); // correct
只需指定二进制模式:
std::string result;
std::fstream fs( "/dev/stdout", std::fstream::in|std::fstream::binary );
while ( !fs.eof() ) {
std::string b;
fs >> b;
result += b;
}
fs.close();
我用以下文件创建的文件测试它:
std::fstream out( "C:\\tmp\\test1.txt", std::fstream::out );
out.write( "aaa\n\0\0bbb\0ccc", 13 );
out.close();
但是你必须使用迭代器(result.begin(),result.end())访问数据,因为c_str()调用将在'\\ 0'上截断
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.