-2

I am writing a program to print the last n characters of a .txt file. I wish to add the ability to run the program from the command line with a -n argument to input the amount of characters to print.

I have tried declaring int main(int argc, char* argv[]) but that seems to accept any amount of arguments and I only need the one -n argument.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
deezy
  • 49
  • 3

2 Answers2

1

To do that, you can use strncmp and strtol:

int main(int argc, char* argv[])
{
     int n = 0;
     if(argc > 1)
     {
        if(!strncmp(argv[1], "-n", 2))
        {
            n = strtoll(argv[1]+2, NULL, 10);
        }
     }
     if(n == 0) /* fail */;
     /* do stuff */
}

This checks if argv has more than just one argument (the name of the program) and then checks for -n, and, if it finds it, converts the number directly after -n to an integer (i.e. -n3 is converted to three).

If you want to accept one argument only and fail otherwise, change argc > 1 to argc == 2.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
1

and I only need the one -n argument. You will need at least 3 arguments if you require the -n argument. (meaning argc - argument count will be 3.)

... This is assuming the -n argument will be followed by an integer value to indicate how many characters are to be read. If the number of characters to be read from your file is 3, it would be called on the command line for example as:

programName.exe -n 3 

This results in the arguments of main(int argc, char* argv[]) being populated as:

argc == 3
argv[] == {"programName.exe", "-n", "3"}

So yes, the C main signature int main(int argc, char* argv[]) will accommodate 1 to many arguments, but that does not exclude it from being used to create a program that will accept only 2 arguments. (The first argument listed by convention is always the executable name of the program the code is compiled into.)

If you would like to have only the one additional argument (which would result in a count of 2 actual arguments), skip including the '-n' and define your Usage as requiring a singe positive digit following the program name:

programName.exe 3

Then code it like this:

int main(int argc, char *argv[])
{
    char *dummy;
    int val;
    if(argc != 2)
    {
        printf("Usage: prog.exe <n> where <n> is a positive integer value.\nProgram will now exit");
        return 0;
    }
    // Resolve value of 2nd argument:
    val = strtol(argv[1], &dummy, 10);
    if (dummy == argv[1] || ((val == LONG_MIN || val == LONG_MAX) && errno == ERANGE))
    {
            //handle error
    }
    //use val to read desired content from file
    ...

    return 0;
}
ryyker
  • 22,849
  • 3
  • 43
  • 87