iyasar
iyasar

Reputation: 1271

getting information from standard output ( C++ )?

How can I read the below information from standard output?

[email protected]\[email protected]\[email protected]\0\0

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

With such code:

string s;
fstream fs("/dev/stdout", fstream::in);
fs >> s;

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

[email protected]@[email protected]@test.com

All \0 and \0\0 are lost.

How can I do that?

Upvotes: 0

Views: 176

Answers (2)

Ilya Denisov
Ilya Denisov

Reputation: 878

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'

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477140

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

Upvotes: 1

Related Questions