WalterC WalterC - 2 months ago 6
Bash Question

Trying to run a C program on Unix but a little confused with how input file is handled

I'm trying to run a C program in a Unix environment and I have an input file as well. The teacher said we can run it by typing in

gcc programName ./a.out inputFile


or

gcc programName ./a.out inputFile > viewFile


My question is: how is this handled within the C program? Like, is the input file being added as a parameter for
main
(or like its name or something) or is it acting like it's reading from
system.in
or something else?

I'm getting a message saying that there's an error opening the input file and I have
int main(int argc, char* argv[])
. If someone could explain what's going on and how the input file is handled, I'd really appreciate it.

Answer

Your professor mentions two ways of calling the file:

  1. ./a.out inputFile
  2. ./a.out inputFile > viewFile

For both forms:

  • argc would be 2.
  • argv[0] would be a string representing the program name,
  • argv[1] would be "inputFile".

POSIX shells interpret > filename to mean redirecting the program's output (specifically stdout) to the given filename.

Command redirections do not appear in the list of arguments from the program's perspective (although there are usually system-specific ways of finding the original command line out).

Comments