Home > Net >  Implementing parsing with the ls command in C
Implementing parsing with the ls command in C

Time:11-13

I'm trying to implement the ls command in C with a few parameters like -a, -l... or -la, but I'm having issues with the parsing, when I use the input I get Segmentation Fault, this is an example of the -a parameter:

int comparator(char *av) {
    int i = 0;
    if (my_strcmp((av[i]), "-a") == 0)
        return 0;
    else
        return 1;
}

int my_ls_a(char *path) {
    int comp = comparator(path);
    DIR *pdirec = opendir(".");
    struct dirent *direc;
    direc = readdir(pdirec);
    
    while (direc != NULL || comp == 0) {
        my_printf("%s  ", direc->d_name);
        direc = readdir(pdirec);
    }
    if ((path = readdir(pdirec)) == NULL)
        my_printf("\n");
    if (pdirec == NULL)
        return (84);
    closedir(pdirec);
    return (0);
}

And this is my main:

int main(int ac, char *av[]) {  
    if (ac == 1)
        my_ls_a(av[0]);
    return 0;
}

I already have all the #include in a .h by the way.

When I only use the main function it works but not when I add the parameter -a.

CodePudding user response:

It's probably better to use getopt() for parameter parsing instead of writing your own parser.

CodePudding user response:

You have undefined behavior in the function comparator in my_strcmp((av[i]), "-a") because av is defined as a char * so you are passing a character where my_strcmp probably expects a pointer.

You should compile with -Wall -Werror to avoid such silly mistakes.

It is unclear why you pass only a single argument to my_ls_a. You should pass both ac and the argument array av and iterate on the arguments to parse the options.

  • Related