在Ubuntu的终端中,通过argv[2]给出的文件名,在一个目录中查找一个文件和它的路径

0 人关注

这里我列出了终端中给出的目录中的所有文件和它们的类型。我想在终端给出一个文件名,如果该文件存在于该文件夹中,我想打印它的名字和路径。我怎样才能做到这一点?

void listDir(char *dirName){
    DIR *dir;
    struct dirent *dirEntry;
    struct stat inode;
    char name[1000];
    dir=opendir(dirName);
    if(dir==0){
        printf("Error in opening the directory\n");
        exit(-1);
    while((dirEntry=readdir(dir))!=0){
        sprintf(name, "%s/%s", dirName, dirEntry->d_name);
        lstat(name, &inode);
        if(S_ISDIR(inode.st_mode)){
            printf("This is a directory: ");
        else if(S_ISREG(inode.st_mode)){
            printf("This is a file: ");
        else if(S_ISLNK(inode.st_mode)){
            printf("This is a link: ");
        printf("%s\n", dirEntry->d_name);
int main(int argc, char **argv){
    struct stat fileMetadata;
    if(stat(argv[1], &fileMetadata) < 0){
        printf("Error in getting information about the file");
        exit(-1);
    if(S_ISDIR(fileMetadata.st_mode)){ //it's a directory
        printf("The content of %s (directory) is:\n", argv[1]);
        listDir(argv[1]);
    else{
        printf("%s it's not a directory\n", argv[1]);
        exit(-1);
    
c
linux
file
ubuntu
yoko
yoko
发布于 2017-06-30
1 个回答
suraj
suraj
发布于 2017-06-30
已采纳
0 人赞同

这将在所有可能的目录和子目录中搜索该文件名。 文件名是在命令行中给出的。 将你的listDir()函数替换为这个函数(这将在所有目录和子目录中搜索文件名并打印其绝对路径)。

void listDir(char * dirName, char *fileName)
        DIR *dir;
        struct dirent *dirEntry;
        struct stat inode;
        char name[1000];
        char buf[PATH_MAX + 1];
        dir=opendir(dirName);
        if(dir==0)
                printf("Error in opening the directory\n");
        printf("file_name : %s\n",fileName);
        while((dirEntry=readdir(dir))!=0)
                if(strcmp(dirEntry->d_name, fileName) == 0)
                        realpath(dirEntry->d_name, buf);
                        printf ("[%s]\n", buf);