Page 75 - C-Language
P. 75

#include <stdlib.h>
         #include <stdio.h>
         #include <errno.h>
         #include <limits.h>

         int main(int argc, char* argv[]) {

             for (int i = 1; i < argc; i++) {
                 printf("Argument %d is: %s\n", i, argv[i]);

                 errno = 0;
                 char *p;
                 long argument_numValue = strtol(argv[i], &p, 10);

                 if (p == argv[i]) {
                     fprintf(stderr, "Argument %d is not a number.\n", i);
                 }
                 else if ((argument_numValue == LONG_MIN || argument_numValue == LONG_MAX) && errno ==
         ERANGE) {
                     fprintf(stderr, "Argument %d is out of range.\n", i);
                 }
                 else {
                     printf("Argument %d is a number, and the value is: %ld\n",
                            i, argument_numValue);
                 }
             }
             return 0;
         }


        REFERENCES:

            •  strtol() returns an incorrect value
            •  Correct usage of strtol


        Using GNU getopt tools


        Command-line options for applications are not treated any differently from command-line
        arguments by the C language. They are just arguments which, in a Linux or Unix environment,
        traditionally begin with a dash (-).


        With glibc in a Linux or Unix environment you can use the getopt tools to easily define, validate,
        and parse command-line options from the rest of your arguments.

        These tools expect your options to be formatted according to the GNU Coding Standards, which is
        an extension of what POSIX specifies for the format of command-line options.


        The example below demonstrates handling command-line options with the GNU getopt tools.


         #include <stdio.h>
         #include <getopt.h>
         #include <string.h>

         /* print a description of all supported options */
         void usage (FILE *fp, const char *path)
         {
             /* take only the last portion of the path */



        https://riptutorial.com/                                                                               51
   70   71   72   73   74   75   76   77   78   79   80