列出指定目录下属于给定用户的所有文件

来源:互联网 发布:单片机校验位计算 编辑:程序博客网 时间:2024/06/05 10:40

要求:给定目录路径和用户名作为输入参数,打印输出该目录下属于该用户的所有文件名。

知识点:

struct passwd * getpwnam(const char * name) 

#include<pwd.h>   

#include<sys/types.h>

getpwnam()用来逐一搜索参数name 指定的账号名称,找到时便将该用户的数据以passwd结构返回。如果返回NULL 则表示已无数据,或有错误发生。

passwd结构体定义如下:

struct passwd

{

char * pw_name;     /* Username. */

char * pw_passwd; /* Password. */

__uid_t -pw_uid;     /* User ID. */

__gid_t -pw_gid;     /* Group ID. */

char * pw_gecos;    /* Real name. */

char * pw_dir;    /* Home directory.*/

char * pw_shell; /* Shell program. */

}

代码:

#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<unistd.h>
#include<errno.h>
#include<dirent.h>
#include<sys/types.h>
#include<pwd.h>
#include<string.h>
#define SIZE 1024
int dir_run(char *path,uid_t uid,char *username)
{        
    DIR *dir;  
    dir = opendir(path);   
    if (dir == NULL)
    {       
        return -1;  
    }
    struct stat st;
    struct dirent *entry;
    char fullpath[SIZE];
    while((entry = readdir(dir)) != NULL)
    {      
        if((strcmp(entry->d_name, ".") == 0) || (strcmp(entry->d_name, "..") == 0))
        {        
            continue;   
        }
        sprintf(fullpath, "%s/%s", path, entry->d_name);     
        if(lstat(fullpath, &st) != 0)
        {          
            continue;
        }
        if(uid==st.st_uid)
        {
            printf("%s\n",entry->d_name);
        }
        if(S_ISDIR(st.st_mode))
        {       
            printf("%s目录下属于给定用户%s的所有文件:\n",entry->d_name,username);
            dir_run(fullpath,uid,username);  
            printf("\n");
        }      
    }   
    closedir(dir);
    return 0;
}
int main(int argc,char*argv[])
{
    struct passwd *pw;
    if(argc!=3)
    {
        printf("参数不正确!正确格式:./main filepath username\n");
        exit(1);
    }
    pw = getpwnam(argv[2]);
    if (!pw)
    {
        printf("%s is not exist\n", argv[2]);
        return -1;
    }
    dir_run(argv[1],pw->pw_uid,argv[2]);
    return 0 ;
}

0 0
原创粉丝点击