0

I'm currently working on my school project and wondered if there is any way to tell if user has written <textfile.txt to the terminal.

Like this: ./project <textfile.txt

My project reads all the lines from the text file to stdin and via scanf works with them. But when I don't use the <textfile.txt "thing", it starts without the data. Instead, I'd like it to write an error and stop the program.

Thanks a lot.

Weather Vane
  • 32,572
  • 7
  • 33
  • 51
Isha
  • 13
  • 4

2 Answers2

2

You might use isatty(3) to detect if your stdin is a terminal.

You could use fstat(2) on STDIN_FILENO, e.g. to detect redirection or pipelines.

Or (on Linux) readlink(2) /proc/self/fd/0 , see proc(5)

I recommend accepting some program argument to override such an auto-detection. Read this.

Be aware that redirection and globbing is done by the shell, see this.

Basile Starynkevitch
  • 216,767
  • 17
  • 275
  • 509
1

On unix systems you can check whether stdin refers to a terminal:

if (isatty(0)) {
    fprintf(stderr, "input was not redirected\n");
    exit(EXIT_FAILURE);
}
melpomene
  • 81,915
  • 7
  • 76
  • 137