0

void my_double_ls(char *dirname)
{
    struct dirent *d;
    struct stat statbuf;
    DIR *dp;
    if ((dp = opendir(dirname)) == NULL)
        exit(1);

    while ((d = readdir(dp)) != NULL)
    {
        if (d->d_ino != 0)
        {
            d->d_name[d->d_namlen] = 0;
            if (stat(d->d_name, &statbuf) == -1)
            {
                printf("%s %d %d %d\n", d->d_name, S_ISDIR(statbuf.st_mode), S_ISREG(statbuf.st_mode), d->d_namlen);

            }
            else
            {
                if (S_ISDIR(statbuf.st_mode))
                {
                    printf("%s *\n", d->d_name);
                }
                else
                {
                    printf("%s\n", d->d_name);
                }
            }
        }
    }

    closedir(dp);
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("wrong argument numbers\n");
        exit(1);
    }
    my_double_ls(argv[1]);
    return 0;
}

I've written like that but when i insert file name and check with stat function
all stat's return value of name of d(dirent) were -1 and S_ISDIR was always true for even if txt file exist what is wrong with that?

evergreen
  • 681
  • 10
  • 22
  • 2
    You're passing `file` rather than `dir/file` to `stat`. That's why `stat` is returning `-1` and setting `errno` to `ENOENT` (`No such file or directory`). – ikegami Oct 13 '20 at 02:21
  • You might want to look at [`fstatat()`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fstatat.html) and [`dirfd()`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/dirfd.html). – Jonathan Leffler Oct 13 '20 at 02:26

0 Answers0