- 论坛徽章:
- 0
|
本帖最后由 anpufeng 于 2013-04-14 21:58 编辑
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <dirent.h>
- #include <string.h>
- #include <strings.h>
- #include <errno.h>
- void list(DIR *d, char *p){
- DIR *dp=(DIR *)d;
- struct dirent *dir;
- char path[256];
- bzero(path,256);
- strcpy(path,p);
- char bufpath[1024];
- bzero(bufpath,1024);
- struct stat st;
- while((dir = readdir(dp)) != NULL){
- strcpy(bufpath,path);
- strcat(bufpath,dir->d_name);
- if (stat(bufpath, &st) == 0) {
- if(S_ISDIR(st.st_mode) && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0) {
- strcat(bufpath,"/");
- printf("test in st_mode");
- printf("%s's size is %-4d bytes\n", bufpath, st.st_size);
- printf("%s's t_blksize is %-4d bytes\n", bufpath, st.st_blksize);
- printf("%s's blocks is %-4d blocks\n", bufpath, st.st_blocks);
- dp=opendir(bufpath);
- list(dp,bufpath);
- } else {
- printf("%s\n",bufpath);
- }
- } else {
- printf("bufpath: %s, dir->d_name: %s errorno: %s\n", bufpath,dir->d_name, strerror(errno));
- }
- }
- }
- int main(int argc,char **argv) {
- char bufpath[256];
- bzero(bufpath,256);
- if(argc!=2) {
- printf("miss argument\n");
- } else {
- strcpy(bufpath,argv[1]);
- int len=strlen(argv[1]);
- if(bufpath[len-1]!='/') {
- strcat(bufpath,"/");
- }
- }
- DIR *dp;
- dp=opendir(bufpath);
- if(dp == NULL){
- printf("%s is not a dir!\n", bufpath);
- }
- list(dp,bufpath);
- }
复制代码 stat()执行的时候要判断是否正确, 不要直接用
另外就是楼上说的好的编程习惯 |
|