Reputation: 9521
I'm learning C programming language and trying to do some basic stuff with it. The problem I faced is how to parse command line arguments. I read this answer and tried to find the library summary for unistd.h
functions int the standard N1570. But unfortunately it is not defined there (Work only for POSIX compliant OS as far as I can understand).
AFAIK Windows is not really POSIX compliant so something like in the answer I referred to above
#include <unistd.h>
int main(int argc, char *argv[]){
int opt;
while((opt = getopt(argc, argv, "ilv") != -1){
//do some with it
}
}
is not really portable.
QUESTION: The only standardized and portable way to parse command line args is to do it yourself?
Upvotes: 3
Views: 5496
Reputation: 140890
Is there a standardized way to parse command line arguments in C?
Yes there is. Not standardized by the C committee, but by others. The most commonly widespread is POSIX with it's Utility Conventions and getopt utility. Using GNU Argument Syntax with argp is just fun and cool. There is also commonly used GNUs getopt_long for supporting long arguments with getopt.
The only standardized and portable way to parse command line args is to do it yourself?
There is none standardized in C11 way to parse command line. The C11 only specifies, that the main arguments are strings, but they're value is just implementation-defined:
If the value of argc is greater than zero, the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup. The intent is to supply to the program information determined prior to program startup from elsewhere in the hosted environment.
The C standard doesn't introduce an abstraction of a "command line", so an abstraction consisting of "command line arguments" and furthermore "command line arguments parsing" is just not defined. I think introducing a standardized way to parse command line arguments is out of scope for a C standard.
The most portable way is to write and use the most portable code. Indeed the most portable code would not use any non-standard C libraries and "do it yourself" in a most portable manner.There is little sense to target all possible architectures and environments. If you are going only for GNU/Linux, I would go with getopt
if you want to stay portable to some crazy environment and for argp
if you want just to target GNU/Linux specific systems. getopt
is really widespread, even a library for embedded systems like newlib has getopt
and getopt_long
implemented. For others, you can just copy/include the code for getopt from other sources into your program, thus protecting against environments that doesn't have it.
Upvotes: 5