简体   繁体   中英

Writing C-programs which can be run with additional arguments from command line

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, eg

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 eg ./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!

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 .

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM