0

My program implements a rudimentary scanner. It should be able to handle both file input and users manually entering input through the command line. My issue is being able to figure out which it is so I can handle it appropriately. Ideas so far:

  1. I can assume there will be at least one whitespace character within a file or in a line of standard input. I'm thinking I could check argv[1] for whitespace, and if there's none, assume it's a file name and open the file.

  2. Alternately, I might try to use this to check if the file exists, open it if so, and handle it as command line entry otherwise.

Is there a simpler option that I'm missing? Are either of these two existing ideas more efficient and reliable than the other?

Community
  • 1
  • 1
HB-
  • 635
  • 2
  • 8
  • 21
  • 3
    Note that filenames may contain whitespaces in them. – Aleks G Oct 14 '14 at 07:30
  • 1
    A typical way for console programs to indicate that the input is to be taken from the standard input is to take `-` as a parameter. For example, if your program is `myprogram`, then you could invoke it as `myprogram inputfile.dat` to process input from the `inputfile.dat` or `myprogram -` to indicate that the input should be taken from `stdin`. – Aleks G Oct 14 '14 at 07:32

1 Answers1

1

The normal way to do this is with command line options.

Some programs require a "filename" but understand - to mean stdin, which works well if the input is expected to have multiple lines.

Some programs require their arguments to be placed on the command line, but understand @FILE to mean that FILE should be opened and read, and its entire contents expanded as if they were on the command line instead.

Some programs usually take arguments on the command line but also have a way to get them from a file, e.g. awk -f FILE reads its commands from FILE rather than the command line.

Some programs usually take a filename containing commands but also offer an explicit option taking commands, e.g. bash -c "echo hello".

This is just a quick survey of some options; which one is best for your application is something you'll need to decide. You'll notice that none of them make use of simple guessing to determine if something is a file (by checking if it exists for example); they're all pretty explicit (the first prevents using files named - but what sort of animal would do such a thing?).

John Zwinck
  • 239,568
  • 38
  • 324
  • 436