我正在學習C編程在Linux中,我寫這個輸出有關文件和目錄的信息,如標準工具「ls」與「-l」,一切正常很好,除了宏S_ISDIR,這是我的代碼。 此外,我的操作系統是薄荷14 x86_64。測試目錄起訴S_ISDIR,但它不起作用
3210回答
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。因此,你必須做反向檢查。
系統調用
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爲您分配內存。
你應該按照手冊中的建議測試stat
和if(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);
}
}
感謝您的回答。但問題仍未解決。 「登出」是一個目錄,但像這樣 模式節目輸出:40755 是不是DIR 鏈接:6 組:1000 用戶:1000 大小:4096 modtime:星期五02月01日17時59分53秒2013 – user1198331
我附加了一個更正的版本。現在一切正常。在您的代碼中,您沒有將文件名傳遞給'stat',但總是目錄名... – user1146332
是否編譯並運行該程序?是否爲您提供正確的輸出? – user1198331
- 1. 測試目錄S_ISDIR行爲不一致
- 2. typemock測試不起作用
- 3. 測試不起作用CakePHP2.0
- 4. PHPunit測試不起作用
- 5. 耙測試不起作用
- 6. 試圖回到目錄,但鏈接不起作用
- 7. 試圖創建一個目錄 - 沒有錯誤,但它不起作用?
- 8. 我試過jQuery的試驗和錯誤,但它不起作用
- 9. 負載測試調試不起作用
- 10. 作爲附件測試不起作用
- 11. selenium.captureEntirePageScreenshot不起作用,但selenium.captureScreenshot起作用
- 12. ON_CALL不起作用,但EXPECT_CALL起作用
- 13. scrollView.requestFocus()返回true,但它不起作用
- 14. html href到https。但它不起作用
- 15. 我得到$ .cookie但它不起作用?
- 16. inspectdb命令但它不起作用
- 17. Mongo DB啓動,但它不起作用
- 18. 使用simpleBlobDetector進行對象檢測,但它不起作用
- 19. 我的.htaccess看起來不錯,但它不起作用
- 20. pytest argparse測試用例不起作用
- 21. 使用雲流測試不起作用
- 22. 嘗試使用hasClass()實現if語句,但它不起作用
- 23. 試圖在cakephp中使用TinyMce,但它不起作用
- 24. 嘗試第一次使用deeplearning4j,但它不起作用
- 25. 試圖用eclipse爲xml運行xslt,但它不起作用
- 26. 試圖使用StreamWriter和StreamReader創建登錄系統,但它不起作用?
- 27. Facebook API:登錄,但仍不起作用
- 28. 錄製聲音看起來不錯,但播放不起作用
- 29. 我試圖讓圖像周圍的文字浮起來,但它不起作用
- 30. RSpec測試不起作用,但它在瀏覽器中效果很好
感謝您的回答,我將我的代碼倒過來,這次它運行良好。 – user1198331