1

I'm learning C-programming and have got stuck on a problem to which I can't find any answer anywhere.

What I want to do is to write a C-program which I can run with additional arguments directly from the terminal, e.g.

cat -n input.txt - nosuchfile.txt input.txt

What I want to know is how I can write any function so I can run it as above (after compilation), so what the program does is perhaps not very important, but for the sake of completeness, cat takes a list of input-files and prints them to stdout. It has full error handling (hence the file nosuchfile.txt), and can also include line numbering (-n) and take input from the standard input (-).

For clarification, I have previously written programs where I can compile the source files, and run the program with e.g. ./cat, and if input is required this has been acquired after this command to start running the program. Thus, the terminal has looked something like this:

gcc ...
./cat
-n input.txt - nosuchfile.txt input.txt

I want to know how to be able to run the program like this

gcc...
cat -n input.txt - nosuchfile.txt input.txt 

Thank you very much!

Jack Kelly
  • 18,264
  • 2
  • 56
  • 81
  • You are asking about argc and argv. You can also look up getopt. However, this is the sort of question that isn't really helpful to others, so I am also voting to close. – Heath Hunnicutt Mar 14 '13 at 05:50
  • possible duplicate of [Handling command line flags in C/C++](http://stackoverflow.com/questions/14737957/handling-command-line-flags-in-c-c) – abelenky Mar 14 '13 at 06:00

2 Answers2

0

There are 2 or 3 well defined parameters for main in most systems:

#include <stdio.h>
int main(int ac, char **av) { printf("%d %s\n", ac, av[0]); return 0; }

would print the number of parameters(+1) and the name of the program. av[1] would contain a pointer to a string containing the first parameter (if ac>1) etc.

The third possible parameter , char **env) (under some systems) would contain a pointer to environment variables.

EDIT The gnu getopt library helps parsing the command lines just as used in unix / gnu utilities in general.

Aki Suihkonen
  • 19,144
  • 1
  • 36
  • 57
0

You can use command line arguments:

#include <stdio.h>

int main( int argc, char *argv[] ) // argc is the (c)ount of arguments, argv is the (v)alues
{
  printf( "\nCommand-line arguments:\n" );

  for( int count = 0 ; count < argc ; count++ )
  {
    printf( "  argument %d = %s\n", count, argv[count] );
  }

  return 0;
}
nvoigt
  • 75,013
  • 26
  • 93
  • 142