使用readdir_r读取目录中的文件并使用qsort进行排序

时间:2014-12-08 22:40:13

标签: c struct qsort readdir getpwuid

我正在尝试用C编写一个程序,该程序从目录中读取文件并检测每个文件的名称,用户,组和大小。每个文件的信息存储在结构数组中,并使用qsort按文件名排序。然后将排序后的文件打印到屏幕上。该程序必须使用readdir_r,getpwuid_r和getgrgid_r。我不明白为了实现我的目标,必须如何实现必须为这些函数的“_r”版本提供的多个参数。我也收到了几个“成员'名称'请求,不是结构或联合”的错误(也出现'size','user'和'group')。

有谁能帮我理解在这种情况下如何正确使用“_r”功能?手册页不够清晰,无法理解。

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <stddef.h>
#include <pwd.h>
#include <grp.h>
#include <string.h>

int main(int argc, char* argv[])
{

DIR *mydir;
struct dirent *myfile;
struct stat mystat;
struct passwd  *pwd;
struct group   *grp;
struct dirent *result;


struct entry
{
    char *name;
    char *user;
    char *group;
    int size;
};

struct entry entries[1024];

if(argc != 2)
{
    perror("must supply a directory");
    return -1;
}

mydir = opendir(argv[1]);
if(mydir==NULL)
{
    perror("Cannot find directory");
    return -1;
}

char buf[1024];
while((myfile = readdir_r(mydir, myfile, )) != NULL)
{
    entries.name = myfile->d_name;
    stat(buf, &mystat);
    entries.size = mystat.st_size;

    /* store owner's name in struct if it is found using getpwuid_r(). */
    if ((pwd = getpwuid_r(mystat.st_uid, , , , ,)) != NULL)
            entries.user = pwd->pw_name;
    else
         perror("user not found");


    /* store group name in struct if it is found using getgrgid_r(). */
    if ((grp = getgrgid_r(mystat.st_gid, , , , ,)) != NULL)
             entries.group = grp->gr_name;
    else
             perror("group not found");


 }

 int cmpfunc( const void *a, const void *b)
 {
     char const *aa = (char const *)a;
     char const *bb = (char const *)b;

     return strcmp(aa, bb);
 }

 qsort(entries, 4, sizeof(int), cmpfunc);

 int i = 0;
 for(int i; i < sizeOf(entries); i++)
 {
        printf("%s %s %llu %s\n", entries.user, entries.group,
        entries.size, entries.name);
 }

        closedir(mydir);

        return 0;
}

1 个答案:

答案 0 :(得分:1)

以下是使用readdir_r()的示例...您应该能够找出其他人 基于这个例子:

#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>

int main(int argc, char *argv[])
{

    DIR *mydir;
    struct dirent myfile;
    struct dirent *result;

    int rc;

    if (argc != 2) {
        perror("must supply a directory");
        return -1;
    }

    mydir = opendir(argv[1]);
    if (mydir == NULL) {
        perror("Cannot find directory");
        return -1;
    }

    while ((rc = readdir_r(mydir, &myfile, &result)) == 0 && result != NULL ) {
        printf("myfile.entryName: -->%s<--  result->d_name: -->%s<--\n",
              myfile.d_name,
              result->d_name);
    }

    closedir(mydir);

}