linux c 关于目录打印的例子,运行结果有问题

crazybullet 2014-06-18 02:51:08
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <dirent.h>

void printDir(char *dir, int depth) {
DIR *dirp;
struct dirent* dirs;
struct stat* statbuf;

if((dirp = opendir(dir)) == NULL) {
printf( "can not open %s\n", dir);
//exit(0);
return; //不起作用,无限循环打印“can not open”
}

chdir(dir);

while((dirs = readdir(dirp)) != NULL) {
lstat(dirs->d_name, statbuf);
if(S_ISDIR(statbuf->st_mode)) {
// deal with directory except . and ..
if(strcmp(".", dirs->d_name) == 0 ||
strcmp("..", dirs->d_name) == 0) {
//printf("continue...\n");
continue; //只起了一次作用,在第二层目录中又会打印 . 和 ..
}
printf("%*s%s/\n", depth, "", dirs->d_name);
// recurse at a new indent level
printDir(dirs->d_name, depth+4);
} else {
printf("%*s%s\n", depth, "", dirs->d_name);
}
}

chdir("..");
closedir(dirp);
}

int main(int argc, char* argv[]) {
char *topDir = ".";
if(argc >= 2) {
topDir = argv[1];
}

printf("print dir of %s:\n", topDir);
printDir(topDir, 0);
printf("-------------end-------------\n");
exit(0);
}


求解释,分数不多,见谅!
...全文
118 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
AndyStevens 2014-06-19
  • 打赏
  • 举报
回复
引用 5 楼 crazybullet 的回复:
DIR *dirp; struct dirent* dirs; 这两个结构体指针没有初始化,就可以用,为什么呢?
因为这两个是系统接口负责分配内存,然后通过返回值把地址传出;而lstat调用中的第二个参数,需要调用者分配好内存,接口往这个地址中写入数据。
crazybullet 2014-06-19
  • 打赏
  • 举报
回复
DIR *dirp; struct dirent* dirs; 这两个结构体指针没有初始化,就可以用,为什么呢?
crazybullet 2014-06-19
  • 打赏
  • 举报
回复
引用 3 楼 Automation_dmu 的回复:
第11行:
  struct stat* statbuf; 
改成
struct stat* statbuf = (struct stat*)malloc(sizeof(struct stat));
记得free~
大神,请恕晚生愚钝,给分前我向知道为什么阿,望不吝赐教!
crazybullet 2014-06-19
  • 打赏
  • 举报
回复
引用 6 楼 Automation_dmu 的回复:
[quote=引用 5 楼 crazybullet 的回复:] DIR *dirp; struct dirent* dirs; 这两个结构体指针没有初始化,就可以用,为什么呢?
因为这两个是系统接口负责分配内存,然后通过返回值把地址传出;而lstat调用中的第二个参数,需要调用者分配好内存,接口往这个地址中写入数据。[/quote] 说的相当清楚了,万分感谢!
AndyStevens 2014-06-18
  • 打赏
  • 举报
回复
第11行:
  struct stat* statbuf; 
改成
struct stat* statbuf = (struct stat*)malloc(sizeof(struct stat));
记得free~
赵4老师 2014-06-18
  • 打赏
  • 举报
回复
system("dir /b /a-d c:\\*.* >d:\\allfiles.txt"); //读文件d:\\allfiles.txt的内容即C:\\下所有文件的名字 system("dir /b /a-d /s c:\\*.* >d:\\allfilesinsub.txt"); //读文件d:\\allfilesinsub.txt的内容即C:\\下所有文件的名字包含子目录 system("dir /b /ad c:\\*.* >d:\\alldirs.txt"); //读文件d:\\alldirs.txt的内容即C:\\下所有子目录的名字 请记住,能用shell命令获取文件、文件夹信息或者操作文件、文件夹最好用shell命令获取或者操作,而不要用各种API获取或者操作,因为当遇到非法文件夹名或非法文件名或非法文件长度、非法文件日期、压缩文件、链接文件、稀疏文件……等各种意料之外的情况时,API会处理的不全面或陷入死循环,而shell命令不会。
赵4老师 2014-06-18
  • 打赏
  • 举报
回复
以下内容仅供参考: linux命令行工具:删除指定目录下指定时间前的某些文件。 可以将包含delbefday的脚本加入crontab中自动定时删除指定目录下指定时间前的某些文件。 含源代码。 http://download.csdn.net/detail/zhao4zhong1/1430808

70,024

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧