Yunyun
Yunyun

Reputation: 21

What does optind do?

I just saw some code using that and I'm curious how it works, I searched and found it's related to getopt but don't know how they're related. I'm new to programming and I'm currently learning C

this is some parts of the code I found, what does this do?

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

#include "helpers.h"

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

    // Define allowable filters
    char *filters = "bgrs";

    // Get filter flag and check validity
    char filter = getopt(argc, argv, filters);
    if (filter == '?')
    {
        fprintf(stderr, "Invalid filter.\n");
        return 1;
    }

    // Ensure only one filter
    if (getopt(argc, argv, filters) != -1)
    {
        fprintf(stderr, "Only one filter allowed.\n");
        return 2;
    }

    // Ensure proper usage
    if (argc != optind + 2)
    {
        fprintf(stderr, "Usage: filter [flag] infile outfile\n");
        return 3;
    }

    // Remember filenames
    char *infile = argv[optind];
    char *outfile = argv[optind + 1];

    // Open input file
    FILE *inptr = fopen(infile, "r");
    if (inptr == NULL)
    {
        fprintf(stderr, "Could not open %s.\n", infile);
        return 4;
    }

    // Open output file
    FILE *outptr = fopen(outfile, "w");
    if (outptr == NULL)
    {
        fclose(inptr);
        fprintf(stderr, "Could not create %s.\n", outfile);
        return 5;
    }

Upvotes: 1

Views: 6815

Answers (2)

rob mayoff
rob mayoff

Reputation: 386038

From the POSIX specification of getopt:

The variable optind is the index of the next element of the argv[] vector to be processed. It shall be initialized to 1 by the system, and getopt() shall update it when it finishes with each element of argv[]. If the application sets optind to zero before calling getopt(), the behavior is unspecified.

So in your case, the if condition is checking that there are exactly two elements of argv left to process, because argc is the number of elements of argv and optind is the index of the next unparsed argument.

Upvotes: 3

AKX
AKX

Reputation: 169407

optind is a global variable used by getopt(3) .

extern int optind;
The variable optind is the index of the next element to be processed in argv. The system initializes this value to 1. The caller can reset it to 1 to restart scanning of the same argv, or when scanning a new argument vector. [...] If there are no more option characters, getopt() returns -1. Then optind is the index in argv of the first argv-element that is not an option.

The snippet you have probably follows a getopt() call, which will have populated some other flag variables from the [flag] described in that usage example.

It's just a check that there are enough (two) "free arguments" in argv after those flags got parsed.

Upvotes: 3

Related Questions