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;
}