Page 77 - C-Language
P. 77

* which means that when the --help option is specified (in its long
                      * form), the help_flag variable will be automatically set.
                      * however, the parser for short-form options does not support the
                      * automatic setting of flags, so we still need this code to set the
                      * help_flag manually when the -h option is specified.
                      */
                     help_flag = 1;
                     break;
                 case 'f':
                     /* optarg is a global variable in getopt.h. it contains the argument
                      * for this option. it is null if there was no argument.
                      */
                     printf ("outarg: '%s'\n", optarg);
                     strncpy (filename, optarg ? optarg : "out.txt", sizeof (filename));
                     /* strncpy does not fully guarantee null-termination */
                     filename[sizeof (filename) - 1] = '\0';
                     break;
                 case 'm':
                     /* since the argument for this option is required, getopt guarantees
                      * that aptarg is non-null.
                      */
                     strncpy (message, optarg, sizeof (message));
                     message[sizeof (message) - 1] = '\0';
                     break;
                 case '?':
                     /* a return value of '?' indicates that an option was malformed.
                      * this could mean that an unrecognized option was given, or that an
                      * option which requires an argument did not include an argument.
                      */
                     usage (stderr, argv[0]);
                     return 1;
                 default:
                     break;
                 }
             }

             if (help_flag) {
                 usage (stdout, argv[0]);
                 return 0;
             }

             if (filename[0]) {
                 fp = fopen (filename, "w");
             } else {
                 fp = stdout;
             }

             if (!fp) {
                 fprintf(stderr, "Failed to open file.\n");
                 return 1;
             }

             fprintf (fp, "%s\n", message);

             fclose (fp);
             return 0;
         }


        It can be compiled with gcc:






        https://riptutorial.com/                                                                               53
   72   73   74   75   76   77   78   79   80   81   82