2013-06-01 20 views
-1

我正在編寫一個dotfile存儲庫管理器,但刪除存儲庫的命令不起作用。 它進入存儲庫文件夾,然後它必須列出所有文件和目錄,以便我可以刪除它們。麻煩在於,它列出了我需要刪除的每個文件或目錄,但它排除了非空的.git。我對其他存儲庫進行了進一步測試,結論是,每個非空目錄的名稱以點開頭都會被忽略,而「普通」點文件則可以。 下面是我會很快描述的有問題的代碼。readdir忽略以點開頭的非空存儲庫

rm_dotfiles_repository時調用庫的名稱,repo_dir(repo)獲取到存儲庫,然後readdir循環啓動。我需要遞歸刪除文件夾,這就是爲什麼我要過濾文件夾和普通的舊文件。請注意,我不排除文件夾...,但我會盡快添加。

#define _XOPEN_SOURCE 500 
#include "repository.h" 
#include "helpers.h" 
#include "nftwcallbacks.h" 

#include <unistd.h> 
#include <stdlib.h> 
#include <dirent.h> 
#include <string.h> 
#include <stdio.h> 
#include <sys/stat.h> 
#include <sys/types.h> 
#include <error.h> 
void rm_dotfiles_repository(char* repo) 
{ 
    repo_dir(repo); 
    /* Remove the repository's files recursively 
    * TODO: Remove the symbolic links in ~ before removing the repo 
    * We remove the repository, target by target */ 
    DIR* dir = NULL; 
    struct dirent* file = NULL; 
    struct stat stat_data; 
    dir = opendir("."); 
    if (dir == NULL) 
    { 
     perror("Error:"); 
     exit(EXIT_FAILURE); 
    } 
    file = readdir(dir); 
    while ((file = readdir(dir)) != NULL) 
    { 
     if (strcmp(file->d_name, ".") != 0 && strcmp(file->d_name, "..") != 0) 
     { 
      /* TODO: why isn't .git listed, even if .gitmodules is listed ? After tests, it seems that .something repositories which are non-empty 
      * aren't listed*/ 
      if(stat(file->d_name, &stat_data)) 
      { 
       perror("Error"); 
       exit(EXIT_FAILURE); 
      } 
      if (S_ISDIR(stat_data.st_mode)) 
      { 
       remove_target(repo, file->d_name); 
      } 
      else 
      { 
       printf("Remove file %s\n", file->d_name); 
      } 
     } 
    } 
    if (closedir(dir)) 
    { 
     perror("Error:"); 
     exit(EXIT_FAILURE); 
    } 
} 

void install_target(char* repo, char* target) 
{ 
    repo_dir(repo); 
    if (nftw(target, install, 4, 0)) 
    { 
     exit(EXIT_FAILURE); 
    } 
} 

void remove_target(char* repo, char* target) 
{ 
    printf("Remove target %s from repo %s\n", target, repo); 
} 

你能幫我找到問題的原因嗎?在此先感謝

編輯:由於墊皮特森問:here的完整代碼,我已經給段是repository.c

+1

任何機會,你可以寫一個完整的獨立的例子,而不是一個包含很多包含非標準文件的代碼片段。例如它應該有一個「主」。 –

+0

我有一個獨立的例子,是的,但有很多代碼。儘管如此,我會做一個主意。 – Mathuin

+0

嗯,我只是刪除了代碼中的「我不需要它」,創建了一個名爲'.git'的目錄並運行了你的代碼,它說,在「刪除」所有其他文件的過程中,「從回購中刪除目標.git「。所以只有兩種可能的情況是你沒有'.git'目錄的讀權限,或者你的系統和我的系統有一些區別...... –

回答

3

您的代碼‘跳過’在目錄中的第一項:

file = readdir(dir); 
while ((file = readdir(dir)) != NULL) 

取出

file = readdir(dir); 

,所有工作得很好。

+0

感謝您的耐心,Mats。錯誤確實在鍵盤和椅子之間...... PEBKAC – Mathuin