简体   繁体   中英

list directory and display details of each file. owner, octal permissions and filename using c

I'm trying to create a method that will do some system calls. It should display the owner of and octal code of each file. but somehow I cant get going. It displays the logged in user name as owner of each file

listContents(char * dir) {

    struct dirent *direntp;
    DIR *dirp;

    if ((dirp = opendir(dir) ) == NULL) 
    {
      perror ("Failed to open directory");
      return 1;
    }

    while((direntp=readdir(dirp))!=NULL) {
        struct stat fileInfo;
        if (stat(direntp->d_name, &fileInfo) == 0);
        {
            struct passwd * pInfo = getpwuid(fileInfo.st_uid);
            if(pInfo!=NULL)
            {
                printf("owner is : %s\toctal permisions is: %o\n", pInfo->pw_name, fileInfo.st_mode);
            }
        }
    }

    while ((closedir(dirp) == -1) && (errno == EINTR)) ;

    return 0;
}

You have an error:

if (stat(direntp->d_name, &fileInfo) == 0); {

shuld be

if (stat(direntp->d_name, &fileInfo) == 0) {

but your version will work only in current directory because you are using stat where your first parameter should be the whole path to file, not only the name. I am adding a little bit revised code:

list_contents (char *dir) {
    struct dirent *direntp;
    DIR *dirp;
    char path[PATH_MAX + 1];
    char fpath[PATH_MAX + 1];

    if ((dirp = opendir(dir)) == NULL) {
        perror ("Failed to open directory");
        return 1;
    }

    strcpy(path, dir);
    strcat(path, "/");

    while (NULL != (direntp = readdir(dirp))) {
        struct stat fileInfo;
        strcpy(fpath, path);
        strcat(fpath, direntp->d_name);

        if (stat(fpath, &fileInfo) == 0) {
            struct passwd * pInfo = getpwuid(fileInfo.st_uid);
            if(pInfo != NULL) {
                printf("%s - owner is : %s\toctal permisions are: %o\n", direntp->d_name, pInfo->pw_name, fileInfo.st_mode);
            }
        }
    }

    closedir(dirp); // edited as chux proposed

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM