tags:

views:

77

answers:

4

Hi to all. I want to redirect console streams to cin,cout and cerr. (its a gui application) Well, I have written this class wich do this but when use cin, cout works no more.

GetLastError says me INVALID_HANDLE VALUE

Can you explain me how fix this ? Thanks

Kconsole.h
class Kconsole
{

    public:

        Kconsole();
        ~Kconsole();                

        void CreateConsole( void );
        void CloseConsole ( void );

    private:


        HANDLE hin;
        HANDLE hout;
        HWND hwnd;

        bool closed;
        bool err;       

        ofstream n_cout;
        ofstream n_cerr; // new streams
        ifstream n_cin;

        streambuf* old_cout;
        streambuf* old_cerr; // old streams
        streambuf* old_cin;

};

Class method:

void Kconsole::CreateConsole( void ){

// create a console window
int ok = AllocConsole();

if ( ok == 0 ) // check console creation
{

    this->err = true;
    return;        
}    

// redirect cout to console window
this->old_cout = cout.rdbuf();    
this->n_cout.open("CONOUT$");    
cout.rdbuf( this->n_cout.rdbuf() );

// redirect cerr
this->old_cerr = cerr.rdbuf();
this->n_cerr.open("CONOUT$");
cerr.rdbuf( this->n_cerr.rdbuf() );

// redirect cin
this->old_cin = cin.rdbuf();
this->n_cin.open("CONIN$");
cin.rdbuf( this->n_cin.rdbuf() );

//// set title
SetConsoleTitle("Console");
this->hwnd = GetConsoleWindow();
//
//// get handles
this->hin = GetStdHandle(STD_OUTPUT_HANDLE);    
this->hout = GetStdHandle(STD_OUTPUT_HANDLE); 
return;}

Main function

int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,intnCmdShow){

 // All application initialization as RegisterClass, CreateWindow...

// CreateConsole Call

cout << "\nTest string"; // ok, writes this in opened console

int n = 0;

cin >> n; // ok, get typed number
n++;

cout << "\n test finished"; // dont outputs nothing to console

// here GetLastError says INVALID_HANDLE_VALUE

cerr << "\n testing cerr" // cerr outputs in console " test finished" and "testing cerr"
}
A: 

It appears that you're opening the same file twice with fstream.

this->old_cout = cout.rdbuf();    
this->n_cout.open("CONOUT$");    // open for writing #1
cout.rdbuf( this->n_cout.rdbuf() );

// redirect cerr
this->old_cerr = cerr.rdbuf();
this->n_cerr.open("CONOUT$");    // open for writing #2
cerr.rdbuf( this->n_cerr.rdbuf() );

Even if your OS supports this, now there are two separate I/O buffers trying to control the file. If you try to use both, it will result in garbled output.

Either send cout and cerr to different files, or use the same filebuf for both.

this->old_cout = cout.rdbuf();    
this->n_cout.open("CONOUT$");    
cout.rdbuf( this->n_cout.rdbuf() );

// redirect cerr
this->old_cerr = cerr.rdbuf();
cerr.rdbuf( this->n_cout.rdbuf() ); // same filebuf

I think this is still a little wonky, but it should be supported by the standard.

Potatoswatter
A: 

Why don't you just make your app a console app? You can still create windows from a console app, but it means there will always be a console, and always be standard input and output streams.

Anthony Williams
+1  A: 

I don't see why you're messing with std::cout et al at all. If you redirect stdout, stderr and stdin to the console you can then call std::ios::sync_with_stdio() to make sure std::cout, std::cerr and std::cin all work. E.g:

// redirect unbuffered STDIN to the console
intptr_t lStdHandle = (intptr_t)GetStdHandle(STD_INPUT_HANDLE);
int hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
FILE *fp = _fdopen( hConHandle, "r" );
*stdin = *fp;
setvbuf( stdin, NULL, _IONBF, 0 );

std::ios::sync_with_stdio();

Here's a great article (with source) that explains it all.

Andreas Magnusson
-1: Don't ever cast pointers to longs.
DeadMG
If you don't understand the code then please don't bother. First of all GetStdHandle() does *not* return a pointer, it returns a handle. Casting a pointer to long is also perfectly reasonable and possible, you just have to know what you are doing and that it's safe to do so, e.g. on an x86 32-bit platform, it's perfectly ok. In this case the code was quoted from the article I mentioned which was written in 1997 so 64-bit consideration were not common back then. I didn't expect nitpicking to this degree, but thanks for reminding me why I stopped answering questions at SO.
Andreas Magnusson
Personally I try to view upvotes/downvotes in relation to the question and this is the second time in two days I've been downvoted by some small thing that's completely unrelated to the original question. I don't consider my response "not useful" in regards to the original question. Anyway thanks for letting me know why I was downvoted but I would personally just settle for a comment if I was just nitpicking on an otherwise useful answer. I would fix my answer just the same.
Andreas Magnusson
Except that in 2010, you have to seriously consider the possibility that sizeof(long) != sizeof(void*), which HANDLE is typedefed as. It's certainly true that casting is not always unsafe, but, it certainly is not always safe and not a habit you should get into. Besides, since you removed the bad code, I see no reason not to change my downvote.
DeadMG
This doesn't make sense. `cin` and `cout` are initially aliased to `stdin` and `stdout`, not to the console. If you redirect to something else (even if it is the console) then `sync_with_stdio` has no effect. In any case, the feature is enabled by default, so simply calling `sync_with_stdio()` at initialization is guaranteed to have no effect.
Potatoswatter
The fact is that the code *is* redirecting `cin`/`cout`/`cerr` to stdio. Instead of just trying to change `cout`, `cerr` and `cin`, this solution also changes `stdout`, `stderr` and `stdin`. By first redirecting stdio to the console, the `sync_with_stdio()` is there as a safe guard I guess (without looking it up I assumed it was of greater importance). I'm not the original author of the article. I posted some code from it to give an idea of it to those too lazy to click on a link. This "kindness" has caused me no end of grief and I will henceforth only post code I have written myself.
Andreas Magnusson
A: 

The trouble is after use cin, cout handle is closed or released. GetLastError says code 6 (ERROR_INVALID_HANDLE)

I have tried open CONOUT$ once as you say, tried open CONERR$ instead CONOUT$ twice, perhaps close CONOUT$ handle manually via CloseHandle and Open it again with GetStdHandle(STD_OUTPUT_HANDLE) or CreateFile.

In all cases, cout don't print anything. Only when use cerr all content remaining is written.

krnl64