Thread: Multiple Command Line Args

  1. #1
    Registered User
    Join Date
    Jul 2002
    Posts
    913

    Multiple Command Line Args

    im trying to write a program that can handle multiple command line args. i have one working version using the unistd.h library but this only works in linux for mei(n windows using Dev-C++ it gives errors using optarg) but this need(seems) to need args to be in a certain order. im new at this but i have tried using a for loop but it just doesnt work out well.

    any advice?

    thanks

  2. #2
    aurė entuluva! mithrandir's Avatar
    Join Date
    Aug 2001
    Posts
    1,209
    Code:
    int main ( int argc, char *argv[] )
    This will allow you to read in arguments from a command line:

    program_name argument_one argument_two

    Something like this will check if you have the correct number of arguments:

    Code:
    if ( argc != 3 )	/* the number of arguments passed in the command must be 3 */
    	{
    		fprintf( stderr, "Too few arguments\n" );
    
    		return ( EXIT_FAILURE );
    >>but this need(seems) to need args to be in a certain order<<

    Obvioulsy you're going to have to evaluate each argument entered. What order you do this in depends on the program, though normally you would check the conditions of each argument in order of entry. Say the first argument must be a file name - you would need to check if it was actually available.

    Code:
    if (( infile = fopen ( argv[1], "rb" )) == NULL )
    {
    fprintf( stderr, "Error opening %s\n", argv[1] );
    
    		return ( EXIT_FAILURE );
    }
    And so on for each argument.

    A little more info on your program would help greatly, because until I actually understand what it is you're trying to do, my help will be limited.

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Fiddle with this for a while. C offers a standard way to deal with command line options:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    static void pause ( void )
    {
      printf ( "Press return to continue" );
      (void)getchar();
    }
    
    int main ( int argc, char **argv )
    {
      int i;
    
      if ( argc != 3 ) {
        fprintf ( stderr, "Usage: program <first name> <last name>" );
        exit ( EXIT_FAILURE );
      }
      printf ( "Hello, " );
      for ( i = 1; i < argc; i++ )
        printf ( "%s%c", argv[i], ( i != argc - 1 ) ? ' ' : '\n' );
      pause();
    
      return EXIT_SUCCESS;
    }
    -Prelude
    My best code is written with the delete key.

  4. #4
    Registered User
    Join Date
    Jul 2002
    Posts
    913
    my program will (attempt) to convert a text file to html. i would like to be able to get options like

    <print a header> <change title> <change output file> inputfile

    but since this is kind of usefull i would like to be able to set option for more than one file and have the order of the options not matter and also not require every one. so far the code just handles one file.

    help!?!?!

  5. #5
    Registered User
    Join Date
    Jul 2002
    Posts
    913
    any one have any ideas?

  6. #6
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Straight from K&R2:
    Code:
    /*
    Usage:
    find -nx pattern
    */
    
       #include <stdio.h>
       #include <string.h>
       #define MAXLINE 1000
    
       int getline(char *line, int max);
    
       /* find: print lines that match pattern from 1st arg */
       int main(int argc, char *argv[])
       {
           char line[MAXLINE];
           long lineno = 0;
           int c, except = 0, number = 0, found = 0;
    
           while (--argc > 0 && (*++argv)[0] == '-')
               while (c = *++argv[0])
                   switch (c) {
                   case 'x':
                       except = 1;
                       break;
                   case 'n':
                       number = 1;
                       break;
                   default:
                       printf("find: illegal option %c\n", c);
                       argc = 0;
                       found = -1;
                       break;
                   }
           if (argc != 1)
               printf("Usage: find -x -n pattern\n");
           else
               while (getline(line, MAXLINE) > 0) {
                   lineno++;
                   if ((strstr(line, *argv) != NULL) != except) {
                       if (number)
                           printf("%ld:", lineno);
                       printf("%s", line);
                       found++;
                   }
               }
           return found;
       }
    This particular example increments the argv pointers, which personally I'm not to keen on doing. But you can also swap that for the array subscripting (argv[i]) method easily.

    The summary of it though, is to simply loop through the argv variable and determine if the first character in each arg starts with a -. If it does, compare the next character to your list of options, and process accordingly.

    Have fun
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  7. #7
    Unregistered
    Guest
    i tried to do a chezzy version of that before but my arguements have args of there own like

    -t TITLE

    and when i use a switch and have a varible become i+1 it doesnt work. i might just be coding wrong but when i print the resaults of at the end of the while(when it stops) ill get some thing like

    -t
    -t TITLE

    or sometime(when i playwith it alittle more)

    -t
    (null) TITLE

    (i cant explaint this last one either, it must be a typo)

    sorry to keep asking this over and over but i dont get it.

    thanks

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826

    Red face

    Well, gee. Since you neglected to post your code, I'll once again have to draw upon my amazing psychic powers and find our where your problem is...

    [meditation]
    ooooooommmmm
    ooooooooooommmmm
    [/meditation]

    Ah hah! I've got it.

    Now all you have to do is use your amazing psychic powers to read my mind, and you'll have the answer on how to fix it.

    If you get tired of using psychic powers, or if you don't have psychic powers like I do, post some code so people without psychic powers can help you.

    Quzah.
    Hope is the first step on the road to disappointment.

  9. #9
    Unregistered
    Guest
    i played with more code for awhile and now nothing works

    Code:
    #include <stdio.h>
    #include <string.h>
    
    char header[2]; /* Just stores the size of the header to print. */
    char title[255];
    char output[255];
    char input[255];
    
    int main(int argc, char *argv[]) {
        int x = 1;
        int y;
        int tmp;
    
        while(argv[x] != NULL) {
            for(y = 0; y <3; ++y) {
                switch( get_arg(argv[x]) ) {
                    case 1: /* Header flag. */
                        strcpy(header, argv[x+1]);
    
                        tmp = check(argc, x, 2);
                        if(tmp != "error")
                            x = tmp;
                        else
                            return 1;
    
                        break;
                    case 2: /* Title flag. */
                        strcpy(title, argv[x+1]);
    
                        tmp = check(argc, x, 2);
                        if(tmp != "error")
                            x = tmp;
                        else
                            return 1;
    
                        break;
                    case 3: /* Output flag. */
                        strcpy(output, argv[x+1]);
    
                        tmp = check(argc, x, 2);
                        if(tmp != "error")
                            x = tmp;
                        else
                            return 1;
    
                        break;
                    case 4: /* Hopefully input file. */
                        strcpy(input, argv[x]);
    
                        tmp = check(argc, x, 1);
                        if(tmp != "error")
                            x = tmp;
                        else
                            return 1;
    
                        break;
                }
            }
    
            printf("\nWhat args were detected\n");
            printf("<header = %s>\t", header);
            printf("<title = %s>\t", title);
            printf("<output = %s>\t", output);
            printf("<input = %s>", input);
        }
    
        return 0;
    }
    
    int get_arg(char arg[]) {
        if( strcmp(arg, "-h") == 0)         /* Print title as header. */
            return 1;
        else if( strcmp(arg, "-t") == 0)    /* Change title. */
            return 2;
        else if( strcmp(arg, "-o") == 0)    /* Change output file. */
            return 3;
        else                                /* Input file? */
            return 4;
    }
    
    int check(int max, int vaule, int inc) {    /* Check to see if all needed args */
        if(vaule + inc < max)                   /* have been typed.                */
            vaule += inc;
        else
            vaule = "error";
    
        return vaule;
    }

  10. #10
    mart_man00
    Guest
    any ideas?

  11. #11
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Your functions need prototypes.

    >if(tmp != "error")
    To compare strings use strcmp()

    >int check(int max, int vaule, int inc)
    >vaule = "error";
    The variable vaule is an int. You cannot assign it to a string literal.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 06-08-2009, 03:03 PM
  2. Phantom redefinition
    By CodeMonkey in forum C++ Programming
    Replies: 6
    Last Post: 06-12-2005, 05:42 PM
  3. Linker errors - Multiple Source files
    By nkhambal in forum C Programming
    Replies: 3
    Last Post: 04-24-2005, 02:41 AM
  4. Replies: 1
    Last Post: 05-01-2003, 02:52 PM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM