0

so I am trying to get all the permissions of my files using the functions stat.

My main problem is that when I send as a path a folder, stat returns me -1, but sending "." gives me all the rights except when it found a folders.

I add two pictures as it might get easier to understand my problem. sending two different av.

char    *g_permissions(struct stat file_stat, char *permissions)
{
    if (!(permissions = malloc(sizeof(char) * 11)))
        return (0);
    permissions[0] = *((S_ISDIR(file_stat.st_mode)) ? "d" : "-");
    permissions[1] = *((file_stat.st_mode & S_IRUSR) ? "r" : "-");
    permissions[2] = *((file_stat.st_mode & S_IWUSR) ? "w" : "-");
    permissions[3] = *((file_stat.st_mode & S_IXUSR) ? "x" : "-");
    permissions[4] = *((file_stat.st_mode & S_IRGRP) ? "r" : "-");
    permissions[5] = *((file_stat.st_mode & S_IWGRP) ? "w" : "-");
    permissions[6] = *((file_stat.st_mode & S_IXGRP) ? "x" : "-");
    permissions[7] = *((file_stat.st_mode & S_IROTH) ? "r" : "-");
    permissions[8] = *((file_stat.st_mode & S_IWOTH) ? "w" : "-");
    permissions[9] = *((file_stat.st_mode & S_IXOTH) ? "x" : "-");
    permissions[10] = '\0';
    return (permissions);
}

void    dir_content(char *path)
{
    char            *permissions;
    DIR             *dir;
    struct dirent   *sd;
    struct stat     fstat;

    dir = opendir(path);
    if (dir == NULL)
        return ;
    while ((sd = readdir(dir)) != NULL)
    {
        stat(sd->d_name, &fstat);
        printf("%i\n",stat(sd->d_name, &fstat));
        if (sd->d_name[0] != '.')
        {
            printf("%s ", g_permissions(fstat, permissions));
            printf("%s\n", sd->d_name);
        }
    }
        closedir(dir);
}

int main(int ac, char **av)
{
    char *test;

    dir_content(av[1]);
    return (0);
}

Thanks for your help and sorry for my bad english!

marlon
  • 17
  • 3
  • `d_name` is relative to `path`. You need to alloc and concat, or else use `fstatat`. – o11c Dec 09 '18 at 19:50
  • `permissions` is allocated but the outer call doesn't see the new buffer. You have to pass the pointer _by address_. And you have a memory leak because you don't save the return char to free it afterwards – Jean-François Fabre Dec 09 '18 at 19:52
  • You know you can use character-literals as well (`'c'`), instead of dereferencing string-literals (`*"c"`)? Makes things simpler. Also, I wonder why you have that second parameter `permissions`, as you always immediately overwrite it... Not to mention that `sizeof(char)` is per definitionem 1. – Deduplicator Dec 10 '18 at 00:24

1 Answers1

0

you need to change your working directory here is the answer https://stackoverflow.com/a/5126055/6416635

int main(int ac, char **av)
{
    chdir(av[1]);
    dir_content(av[1]);
    return (0);
}
ben abdo
  • 16
  • 1
  • 5