开发者

getting information from standard output ( C++ )?

开发者 https://www.devze.com 2023-04-12 10:00 出处:网络
How can I read the below information from standard output? Fmail@yasar.com\\0Tketo@keeto.com\\0Tmail@lima.com\\0\\0

How can I read the below information from standard output?

Fmail@yasar.com\0Tketo@keeto.com\0Tmail@lima.com\0\0

I want to have the entire information, including the \0 characters.

With such code:

string s;
fstream fs("/dev/开发者_如何学JAVAstdout", fstream::in);
fs >> s;

If I write s to a file I get this output:

Ftest555@itap.gov.trTislam.yasar@inforcept.comTaa@test.comTbb@test.com

All \0 and \0\0 are lost.

How can I do that?


This is just a matter of processing the output correctly in your shell.

Imagine this:

cat file_with_nulls

This will recklessly print the content of file_with_nulls to the console, and of course the console may not be equipped to display non-printable characters. However, the following works:

cat file_with_nulls > otherfile

This will create a perfect copy of file_with_nulls.

The same works with your program. You can write anything you want to the standard output. But don't expect your terminal or console to do anything useful with it! Rather, redirect the output to a file and all is well:

./myprog > output.bin

Note that the C string operations don't usually work with null bytes, so in C you should use fwrite(). In C++, strings can contain any character, so std::cout << str; always works. However, constructing an std::string from a C character array stops at the null byte, so you have to use a different constructor:

char cstr[] = { 'H', 'e', 0, 'l', 'l', 'o', 0 };

std::string s1(cstr);  // wrong, gives you "He"
std::string s2(cstr, sizeof(cstr));  // correct


just specify binary mode:

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();

I test it with file created by:

std::fstream out( "C:\\tmp\\test1.txt", std::fstream::out );
out.write( "aaa\n\0\0bbb\0ccc", 13 );
out.close();

But then you'll have to access data with iterators (result.begin(), result.end()) because c_str() call will truncate on '\0'

0

精彩评论

暂无评论...
验证码 换一张
取 消