Reputation: 31
I am writing a program that is a custom version of ls with some options. The options can be inputted as "-i" or as something like "-ilR". This portion of my code iterates through the command line arguments and sets a struct accordingly. Except if I run the program with "./myProgram -i Directory" it doesn't go into the test print I have set up.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/fcntl.h>
#include <stdbool.h>
#include <string.h>
struct optionArguments{
bool argumenti;
bool argumentl;
bool argumentR;
};
int main(int argc, char* argv[]){
struct optionArguments options;
options.argumenti = false;
options.argumentl = false;
options.argumentR = false;
for(int i = 1; i<argc-2; i++){
for(int j = 0; j<strlen(argv[i]); j++){
char chr = argv[i][j];
if(chr == 'i'){
options.argumenti = true;
}
if(chr == "l"){
options.argumentl = true;
}
if(chr == "R"){
options.argumentR = true;
}
}
}
if(options.argumenti){
printf("OPTION I\n");
}
}
any help/advice is greatly appreciated
edit: I just put a test print inside of the second loop and it doesn't print anything at all so the second loop isn't even running.
Upvotes: 0
Views: 52
Reputation: 733
It will be much simpler if you use getopt()
function designed to handle command-line argument parsing.
Note: Since you have already included unistd
library so using getopt
which will be much wiser, otherwise, there are other implementations available as well like argp()
Here is a program which uses getopt
from the POSIX C Library unistd
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/fcntl.h>
#include <stdbool.h>
#include <string.h>
struct optionArguments{
bool argumenti;
bool argumentl;
bool argumentR;
};
int main(int argc, char* argv[]){
struct optionArguments options;
options.argumenti = false;
options.argumentl = false;
options.argumentR = false;
int opt;
while ((opt = getopt(argc, argv, "ilR")) != -1) {
switch (opt) {
case 'i': options.argumenti = true; break;
case 'l': options.argumentl = true; break;
case 'R': options.argumentR = true; break;
default:
fprintf(stderr, "Usage: %s [-ilR] \n", argv[0]);
exit(EXIT_FAILURE);
}
}
if(options.argumenti){
printf("OPTION I\n");
}
if(options.argumentl){
printf("OPTION l\n");
}
if(options.argumentR){
printf("OPTION R\n");
}
}
For other ways of implementation visit: Parsing command-line arguments in C?
Upvotes: 1