2010-11-17 66 views
66

我想在Linux上編寫一個ftp服務器。在這個問題上,我怎麼能通過C程序列出終端目錄中的文件?也許我可以使用exec函數來運行find命令,但我希望將文件名作爲字符串發送給客戶端程序。我怎樣才能做到這一點?如何列出C程序中的目錄中的文件?

感謝您的回答。

回答

128

一個例子,可用於POSIX兼容的系統:

/* 
* This program displays the names of all files in the current directory. 
*/ 

#include <dirent.h> 
#include <stdio.h> 

int main(void) { 
    DIR *d; 
    struct dirent *dir; 
    d = opendir("."); 
    if (d) { 
    while ((dir = readdir(d)) != NULL) { 
     printf("%s\n", dir->d_name); 
    } 
    closedir(d); 
    } 
    return(0); 
} 

要注意的是這樣的操作是依賴於平臺中C.

來源:http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608

+0

現在和這麼容易就可以了。再次感謝您的回答。 – cemal 2010-11-17 13:33:52

+8

如果你喜歡它,請驗證它;) – 2010-11-17 16:50:58

+0

工程就像魅力! – asprin 2013-02-14 10:57:27

27

一個微小除了JB Jansen's answer - 在主要readdir()循環我想補充一點:

if (dir->d_type == DT_REG) 
    { 
    printf("%s\n", dir->d_name); 
    } 

只需檢查它是否真的是文件,而不是(sym)鏈接,目錄或其他。

備註:關於struct dirent的更多內容請參考libc documentation

+3

撇開:並不是所有的平臺都會填寫'd_type',但Linux和BSD將(我知道這個問題是標籤爲Linux,只是延長了答案);即使這樣,不支持所有*文件系統統一*,但它應該適用於大多數FS。 – omninonsense 2016-07-12 06:52:37

3

這是一個完整的程序如何遞歸地列出文件夾的內容:

#include <dirent.h> 
#include <stdio.h> 
#include <string.h> 

#define NORMAL_COLOR "\x1B[0m" 
#define GREEN "\x1B[32m" 
#define BLUE "\x1B[34m" 



/* let us make a recursive function to print the content of a given folder */ 

void show_dir_content(char * path) 
{ 
    DIR * d = opendir(path); // open the path 
    if(d==NULL) return; // if was not able return 
    struct dirent * dir; // for the directory entries 
    while ((dir = readdir(d)) != NULL) // if we were able to read somehting from the directory 
    { 
     if(dir-> d_type != DT_DIR) // if the type is not directory just print it with blue 
     printf("%s%s\n",BLUE, dir->d_name); 
     else 
     if(dir -> d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0) // if it is a directory 
     { 
     printf("%s%s\n",GREEN, dir->d_name); // print its name in green 
     char d_path[255]; // here I am using sprintf which is safer than strcat 
     sprintf(d_path, "%s/%s", path, dir->d_name); 
     show_dir_content(d_path); // recall with the new path 
     } 
    } 
    closedir(d); // finally close the directory 
} 

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

    printf("%s\n", NORMAL_COLOR); 

    show_dir_content(argv[1]); 

    printf("%s\n", NORMAL_COLOR); 
    return(0); 
}