2014-12-21 33 views
0

我給出了具有多個子目錄的目錄路徑。每個子目錄都有一個名爲「st」的文件。我試圖從每個子目錄讀取每個st文件,但我總是在調用fopen時收到一個NULL指針?閱讀子目錄中的文件

我的代碼:

int main(){ 

DIR *dir; 
struct dirent *ent; 
FILE *st; 

dir=opendir("/home/me/Desktop/dir/"); 

while((ent=readdir(dir)) != NULL){ 

    if(ent->d_type == DT_DIR && strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0){ 

     DIR *subDir = opendir(ent->d_name); 

     st = fopen("st", "r"); 

     if(st == NULL){ 
      perror("doesn't exist"); 

     } 

    } 

} 
closedir(dir); 

}  

回答

1

的問題是,在end->d_name名稱是「文件」目錄內的只是名字,它不是完整的路徑,這意味着你要

DIR *subDir = opendir(ent->d_name); 
通話

試圖找到當前目錄中的目錄。

您需要將您傳遞給第一個opendir調用的路徑添加到新路徑部分。

+0

然後,我甚至需要創建另一個direcotroy指針(DIR * subDir),或者我可以只更改第一個(DIR * dir)? – Matthew

+0

都不是。只需連接名稱。 – abligh

+1

根本問題 - 長期無法進行任何調試。 –