Spidey
Spidey

Reputation: 2589

How to access the default stdin while using file redirection?

I need to run a script and have access to the default stdin (terminal input) in my program. I could do ./program "script", opening and parsing the script through the program, but I want to make it POSIX style, accepting input from pipes or from redirection.

I mean, since my program is a parser, I could run ./program, type the script and still use stdin (in a scanf, for example). But I'd like to run ./program < script and still be able to use stdin (in a scanf).

My program is a simplified Pascal interpreter, that's why I need to run read(x) and write(x) in my scripts.

Yes, it's homework (the intepreter), but the doubt just popped up in the brainstorming process.

Upvotes: 2

Views: 1250

Answers (3)

mark4o
mark4o

Reputation: 61013

The current controlling terminal can be accessed using /dev/tty, even if stdin has been redirected.

Upvotes: 2

Nick Lewis
Nick Lewis

Reputation: 4240

ttyname(0) will return the filename of the current terminal associated with stdin. You can then open that and read from it.

Upvotes: 1

Brian Arnold Sinclair
Brian Arnold Sinclair

Reputation: 3833

If I understand what you're asking, you're asking for the ability to take in interactive input from a user when using file redirection, like the ./program < script bit above.

I don't believe there's a way to do that. A POSIX system will feed the script in via stdin and that's that. No interaction from the user.

It's also worth noting that you don't have to do anything special to realize that. Just treat stdin like you normally would. You don't have to think about whether it's coming in interactively or from a file, which is really quite nice.

Upvotes: 0

Related Questions