Hi, all
How to distinguish difference between stdin and string supplied with “<”.
I care only about Windows platform, so th difference is new line chars "\r\n" , is this the only way to catch what is the case here, checking winBuffer for \r\n ? or there is another way ? I really need to know how string was entered to implement something like:
1 2 3 4 5 6 7 8 9
.....
.....
Cin.getline (WinBuffer, SzBuffer)
....
If WinBuffer has a \r\n // stdin with ENTER
Plan A;
Else // with "<" redirection
Plan B;
.....
Sorry I’m bit new to cpp (like 90%:-), so appreciate you help with syntax, my class officially will start in Jan only and I really want knock it down before. Some samples on www I still can’t get.
#ifdef _WIN32
#define NOMINMAX
#include <windows.h>
bool isconsole( unsigned id )
{
static DWORD handles[] = {
STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
};
DWORD foo;
if (id > 2) returnfalse;
return GetConsoleMode( GetStdHandle( handles[ id ] ), &foo ) != 0;
}
#else
#include <unistd.h>
#ifndef ISATTY
/* Assume that the standard isatty() is defined */
#define ISATTY isatty
#else
/* The user has defined something unique. Prototype it. */
int ISATTY( int );
#endif
bool isconsole( unsigned id )
{
staticint filenos[] = { STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO };
if (id > 2) returnfalse;
return ISATTY( filenos[ id ] );
}
#undef ISATTY
#endif
The *nix code makes pains to be as portable as possible -- as not all systems provide a sane isatty() implementation -- or they do not prototype it in <unistd.h> -- so we give the user the build option to make things work on their system.
To use it, it is as simple as:
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
usingnamespace std;
// Either cut and paste the above code here,
// or put it in its own .cpp and #include a header with a proper prototype,
// or put it in its own .cpp and put a proper prototype here.
int main()
{
if (isconsole( 0 )) cout << "Stdin is a human. (Probably.)\n";
else cout << "Stdin is a file.\n";
return 0;
}
And here's a sample run for you:
D:\prog\cc\foo>a
Stdin is a human
D:\prog\cc\foo>a < a.cpp
Stdin is a file
D:\prog\cc\foo>