2014-01-27 16 views
0

我想列出一個目錄中的檔案,它的工作原理。問題是如果我在「。」。我想列舉「./hello」中的te文件,例如「。」,(ls -l hello)。問題是我不知道如何添加到統計的完整路徑,任何人都可以幫助我嗎?我有這樣的代碼:在C 2.0中讀取目錄stat錯誤

else if(strcmp(O->argv[1], "-l")==0){ 
    if(O->argv[2]==NULL){ 
     dir=getcwd(buffer,256); 
     printf("%s \n",dir); 
    } 
    else { 
    dir=getcwd(buffer,256); 
    strcat(dir,"/"); 
    strcat(dir,O->argv[2]); 
    printf("%s \n",dir); 
    } 
    if ((pdirectorio=opendir(dir)) == NULL) //abrir directorio 
    printf("Error al abrir el directorio\n"); 
    else { 
    while((directorio=readdir(pdirectorio))!= NULL){ 
     if((stat(directorio->d_name,&info)) == -1) 
      printf("Fin de directorio.\n"); 
     else {...} 

回答

0

只是將從readdir()獲得的文件名連接到您正在遍歷的目錄的名稱。沿着以下幾條線:

#include <stdio.h> 
#include <string.h> 
#include <dirent.h> 
#include <sys/stat.h> 

#define PATH_MAX 1024 

int main(int argc, char **argv) { 
    DIR *d; 
    struct dirent *e; 
    char fullpath[PATH_MAX]; 
    struct stat st; 

    if(argc > 1) { 
    if((d = opendir(argv[1])) == NULL) return 1; 
    } else 
    return 2; 

    while ((e = readdir(d)) != NULL) { 
    snprintf(fullpath, PATH_MAX, "%s/%s", argv[1], e->d_name); 
    if((stat(fullpath, &st)) == 0) 
     printf("Did stat(%s) and got block count %u.\n", 
     fullpath, st.st_blocks); 
    } 
}