2013-02-01 27 views
0

我正在學習C編程在Linux中,我寫這個輸出有關文件和目錄的信息,如標準工具「ls」與「-l」,一切正常很好,除了宏S_ISDIR,這是我的代碼。 此外,我的操作系統是薄荷14 x86_64。測試目錄起訴S_ISDIR,但它不起作用

​​3210

回答

0

user1198331的更正的stat是正確的。通常檢查所有系統調用返回值以避免錯誤是一種很好的做法。

不過,在你的原代碼,我覺得這部分是錯誤的:

if(S_ISDIR(t->st_mode)==0) 
    printf("Is a dir\n"); 
else 
    printf("Is not a dir\n"); 

你考慮到,如果S_ISDIR(T-> ST_MODE)返回0,它是一個目錄,但實際上,S_ISDIR(T - > st_mode)如果t指向的文件是而不是目錄,則返回0。因此,你必須做反向檢查。

+0

感謝您的回答,我將我的代碼倒過來,這次它運行良好。 – user1198331

0

系統調用

int stat(const char *path, struct stat *buf); 

不會爲*buf分配內存。

你要麼留在你的宣言

struct stat *buf; 

,並在您不需要buf anylonger的地方與free

buf = (struct stat *) malloc(sizeof(struct stat)); 

分配用手內存和釋放內存

或者您將聲明更改爲

struct stat buf; 

並讓c爲您分配內存。

你應該按照手冊中的建議測試statif(stat(t,&buf) < 0)的故障。

另一個錯誤是,您不會將文件名傳遞給stat,而是傳遞目錄名稱。

我附加了你的代碼的修正版本。


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

void do_ls(char []); 

void show_file_info(struct stat *t){ 
    printf("mode: %o\n",t->st_mode); 
    if((t->st_mode & S_IFMT) == S_IFDIR) 
     printf("Is a dir\n"); 
    else 
     printf("Is not a dir\n"); 
    printf("links: %d\n",t->st_nlink); 
    printf("group: %d\n",t->st_gid); 
    printf("user: %d\n",t->st_uid); 
    printf("size: %d\n",t->st_size); 
    printf("modtime: %s\n",ctime(&t->st_mtime)); 
} 

int main(int num,char *a[]){ 
    if(num==1){ 
     do_ls("."); 
    } 
    else{ 
     while(--num){ 
      printf("%s :\n",*++a); 
      do_ls(*a); 
     } 
    } 
} 

void do_ls(char dirname[]){ 
    DIR *tem=opendir(dirname); 
    struct dirent *direntp; 
    struct stat buf; 
    char t[256]; 

    if(tem==NULL){ 
     fprintf(stderr,"ls: cannot open %s\n",dirname); 
    } 
    else{ 
     while((direntp=readdir(tem))!=NULL){ 
      strcpy(t,dirname); 
      printf("%s\n",direntp->d_name); 
      strcat(t,"/"); 
      strcat(t,direntp->d_name); 
      if(stat(t,&buf) < 0){ 
       perror(""); 
       break; 
      } 
      else{ 
       show_file_info(&buf); 
      } 
     } 
     closedir(tem); 
    } 

} 
+0

感謝您的回答。但問題仍未解決。 「登出」是一個目錄,但像這樣 模式節目輸出:40755 是不是DIR 鏈接:6 組:1000 用戶:1000 大小:4096 modtime:星期五02月01日17時59分53秒2013 – user1198331

+0

我附加了一個更正的版本。現在一切正常。在您的代碼中,您沒有將文件名傳遞給'stat',但總是目錄名... – user1146332

+0

是否編譯並運行該程序?是否爲您提供正確的輸出? – user1198331

相關問題