1

In Windows, there exists a console trick

someprogram.exe < input.txt

which makes the program to get the input from input.txt whenever there is a input request. I want my program to behave differently when the input is read from another file. Is there are a way to do that? How?

cngkaygusuz
  • 1,456
  • 2
  • 12
  • 17
  • What do you mean `read by another file`? Do you you mean you want to check if the input came from a `file via the console`? Like your example? – gideon Mar 18 '12 at 16:13
  • 2
    If you want to detect whether the program’s standard input and output are hooked up to a console (TTY) or a pipe, you’re out of luck: there is no standard (and non-hackish) way to do this in C++. – Jon Purdy Mar 18 '12 at 16:32

2 Answers2

1

I don't think so(not sure though), but here is an alternative (error checking omitted):

int main(int argc, char **argv)
{
    std::istream * pstream = &std::cin;

    std::ifstream fin;
    if (argc > 1)
    {
        fin.open(argv[1]);
        pstream = &fin;
    }

    // use pstream instead of cin
}

Then you pass the name of the file as a command line argument.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
  • 1
    `pstream` could be a reference type if you used the conditional operator to initialize it. – Emile Cormier Mar 18 '12 at 16:21
  • @Emile: No, that will make problems. You can't conditionally assign an existing variable or a temporary to a reference. The existing variable will either be copied (const-ref, error with uncopyable iostreams) or moved (rvalue ref). The conditional operator only retains type identity if the two operands are exactly the same type and value category. In this case, they're not (either lvalue vs prvalue or xvalue vs prvalue), making the type of the expression a non-reference `std::istream` type of prvalue category (the common type of both operands). – Xeo Mar 18 '12 at 19:16
  • @Xeo: I don't know about all that value category business, but this works fine in GCC 4.7, with the expected behavior: `std::istream & stream = (argc > 1) ? (fin.open(argv[1]),fin) : std::cin;` – Benjamin Lindley Mar 18 '12 at 21:11
  • According to this (http://stackoverflow.com/questions/9200087/initializing-reference-variables-with-the-conditional-operator), the problem is when you attempt to initialize a non-const reference with a r-value expression. – Emile Cormier Mar 18 '12 at 21:17
  • @Emile: That is an entirely different thing. Benjamin: Ah, yeah, that would work, if you create the `std::ifstream` variable beforehand. – Xeo Mar 18 '12 at 22:20
0

Yes, use the function isatty available on most platforms. Looks like it is now called _isatty in windows (not sure why).

edA-qa mort-ora-y
  • 30,295
  • 39
  • 137
  • 267