2017-06-30 6 views
0

ここでは、すべてのファイルとそのタイプを端末で指定されたディレクトリからリストします。私は端末にファイル名を与えたいと思います。もしそのファイルがそのフォルダにあれば、その名前とそのパスを表示したいと思います。どうすればいい?ディレクトリ内のファイルとそのパス、argv [2]で与えられたファイル名、Ubuntuの端末から

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); 
    } 

} 

答えて

0

これは、すべての可能なディレクトリとサブディレクトリのファイル名を検索します。 ファイル名はコマンドラインで指定します。 は、この(これはすべてのディレクトリとサブディレクトリ内のファイル名を検索し、その絶対パスを出力します)にごLISTDIR()関数を置き換えますのrealpath()関数に

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); 
       } 

     } 
} 

このヘッダファイルをインクルード:

#include <sys/stat.h> 
#include <limits.h> 
+0

最後に、動作しています。どうもありがとうございました ! – Yoko

関連する問題