-3

I know, if ran in bash, my program is supposed to able to handle arguments like (where a.out is the name of file):

$ a.out <inputFile

Does this mean that inputFile is argv[1]? If so, what is the data type of argv[1] in case I need to pass it in to some other function? Would I read it using something like: FILE *fopen( const char * filename, const char * mode );

OR

Does that mean I have to accept input from user getchar() or something?

How do I deal with such situations?

Ava Soyet
  • 1
  • 1
  • 1
    [This](https://stackoverflow.com/questions/12812579/how-redirection-internally-works-in-unix) may be helpful – Gealber Dec 02 '20 at 00:53

4 Answers4

2

There's two ways to receive input:

  • Via STDIN, which is a pre-defined filehandle (fd 0 or STDIN_FILENO) you can read from at any time.
  • Via command-line arguments passed by argv

The shell interprets redirection operators to adjust what STDIN actually is, so by the time the program runs the only arguments left are:

"a.out"

The redirection is gone. It's just "piped" into STDIN.

Shell operators like <, > and | are interpreted by the shell before your program is run. The same goes for interpolation like $ variables and other shell-specific functions.

tadman
  • 208,517
  • 23
  • 234
  • 262
2

The command

./a.out < inputFile

isn't passing arguments to the program, instead if does redirection.

That means the shell will set up standard input (stdin, which e.g. scanf reads from) in your program to read from the redirected file.

To pass an actual argument to the program you need to run it as:

./a.out inputFile

In this case argc will be equal to 2, and argv[1] will be the string "inputFile". Which you can then pass on to e.g. fopen.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

You need to pass a path to the c program then use fopen()

0

Using "<" means you are redirecting standard input of your process to be read from inputFile. So, all the standard read routines (getchar(), cin << ...) can be used.

If you omit "<", then inputFile becomes command argument and it is passed as part of char* argv[] to your main. After checking argc, validating file exists etc., you can use file reading routines, like fopen.

quantotto
  • 31
  • 4