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
  • 33,872
  • 7
  • 36
  • 56
Isha
  • 13
  • 4
  • For some reason it didn't show the part with " – Isha Oct 21 '17 at 18:28
  • @Isha Because that looks like an HTML tag. – melpomene Oct 21 '17 at 18:28
  • 1
    Could you please stop wrecking the formatting? – melpomene Oct 21 '17 at 18:29
  • Your program does not need to know where the file is coming from. If the use uses file redirection {<} then this file will be redirecting into stdin. All your program needs to do is read from std. If you want to know if they didn't use redirection, then you can check argc, and it will equal 2 if they have specified a file name rather than redirection (since redirection does not count as a parameter). To get the file name in this place, it will be stored in argv[1] – ScottK Oct 21 '17 at 18:31
  • I'm sorry for the duplication... Didn't look carefully enough. But thanks anyway, helped a lot! :) – Isha Oct 21 '17 at 19:01

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
  • 223,805
  • 18
  • 296
  • 547
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
  • 84,125
  • 8
  • 85
  • 148