Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

How can I open files mentioned on the command line, and parse option flags?

0
Posted

How can I open files mentioned on the command line, and parse option flags?

0

Here is a skeleton which implements a traditional Unix-style argv parse, handling option flags beginning with -, and optional filenames. (The two flags accepted by this example are -a and -b; -b takes an argument.) #include #include #include main(int argc, char *argv[]) { int argi; int aflag = 0; char *bval = NULL; for(argi = 1; argi < argc && argv[argi][0] == '-'; argi++) { char *p; for(p = &argv[argi][1]; *p != '\0'; p++) { switch(*p) { case 'a': aflag = 1; printf("-a seen\n"); break; case 'b': bval = argv[++argi]; printf("-b seen (\"%s\")\n", bval); break; default: fprintf(stderr, "unknown option -%c\n", *p); } } } if(argi >= argc) { /* no filename arguments; process stdin */ printf(“processing standard input\n”); } else { /* process filename arguments */ for(; argi < argc; argi++) { FILE *ifp = fopen(argv[argi], "r"); if(ifp == NULL) { fprintf(stderr, "can't open %s: %s\n", argv[argi], strerror(errno)); continue; } printf("processing %s\n", argv[argi]

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123