c – Why am I unable to access File Permissions using scandir?


When I am in a different directory and try to use the following function on a certain folder/directory (i.e., when char *directory != the directory i am in), I end up not being able to print the details of the contents of the folder (char *directory).

Error: No such file or directory found

int LSL(char *directory, int A)
{
    struct dirent **LIST;
    struct stat ST;

    int NUM = scandir(directory, &LIST, 0, alphasort);
    if (NUM < 0)
    {
        perror("error in ls");
        return 0;
    }

    for (int i = 0; i < NUM; i++)
    {
        if (LIST(i)->d_name(0) == '.' && A == 0)
        {
            continue;
        } else if (stat(LIST(i)->d_name, &ST) == 0)
        {
            printf("%c", (S_ISDIR(ST.st_mode)) ? 'd' : '-');
            printf("%c", (ST.st_mode & S_IRUSR) ? 'r' : '-');
            printf("%c", (ST.st_mode & S_IWUSR) ? 'w' : '-');
            printf("%c", (ST.st_mode & S_IXUSR) ? 'x' : '-');
            printf("%c", (ST.st_mode & S_IRGRP) ? 'r' : '-');
            printf("%c", (ST.st_mode & S_IWGRP) ? 'w' : '-');
            printf("%c", (ST.st_mode & S_IXGRP) ? 'x' : '-');
            printf("%c", (ST.st_mode & S_IROTH) ? 'r' : '-');
            printf("%c", (ST.st_mode & S_IWOTH) ? 'w' : '-');
            printf("%c ", (ST.st_mode & S_IXOTH) ? 'x' : '-');

            printf("%2ld ", (unsigned long) (ST.st_nlink));

            printf("%s ", (getpwuid(ST.st_uid))->pw_name);
            printf("%s ", (getgrgid(ST.st_gid))->gr_name);

            printf("%5lld ", (unsigned long long) ST.st_size);

            char timer(14);
            strftime(timer, 14, "%h %d %H:%M", localtime(&ST.st_mtime));
            printf("%s ", timer);

            printf("%sn", LIST(i)->d_name);
        } else
        {
            perror("error in ls -l");
        }
    }

    fflush(stdout);
    return 0;
}

P.S.: This is a part of my shell program, meant to execute ls (-a -l) (dir).

Case 1: I am in ~

enter image description here

Case 2: I am not in ~

enter image description here