It's UWAweek 48

help2002

This forum is provided to promote discussion amongst students enrolled in CITS2002 Systems Programming.
Please consider offering answers and suggestions to help other students! And if you fix a problem by following a suggestion here, it would be great if other interested students could see a short "Great, fixed it!"  followup message.

Displaying selected article
Showing 1 of 919 articles.
Currently 6 other people reading this forum.


 UWA week 40 (2nd semester, week 10) ↓
SVG not supported

Login to reply

👍x1
helpful
4:12am Thu 6th Oct, Christopher M.

"Lloyd Na" <23*3*1*[email protected]*u*e*t*u*a*e*u*a*> wrote:
> However, I couldn't find a reason for this nor an example showcasing getopt() with the above two lines of code on the internet. > Does anyone know why we should include those two lines? Or anyone know where I can read up on this in case I wasn't searching properly.
Internet searching always performs poorly with the wrong keywords. But you do have a computer and compiler in front of you, so why not experiment?
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>

#define OPTLIST         "abc"

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

    opterr      = 0;
    while((opt = getopt(argc, argv, OPTLIST)) != -1)   {
        if(opt == 'a' || opt == 'b' || opt == 'c') {
            printf("valid option '%c'\n", opt);
        }
        else {
            printf("invalid option '%c'\n", opt);
            exit(1);
        }
    }

    printf("BEFORE:\n");
    for(int a=0 ; a<argc ; ++a) {
        printf("  [%i] %s\n", a, argv[a]);
    }

    argc  -= optind;
    argv  += optind;

    printf("AFTER:\n");
    for(int a=0 ; a<argc ; ++a) {
        printf("  [%i] %s\n", a, argv[a]);
    }

    return 0;
}

The University of Western Australia

Computer Science and Software Engineering

CRICOS Code: 00126G
Written by [email protected]
Powered by history
Feedback always welcome - it makes our software better!
Last modified  1:17AM Sep 14 2022
Privacy policy