当前位置:  技术问答>linux和unix

读一个目录流的时候是不是一定要再该目录下

    来源: 互联网  发布时间:2017-03-27

    本文导语:  #include #include #include #include #include #include #include void print_dir(char *dir,int depth) { DIR *dp=opendir(dir); struct dirent *dirent; struct stat stat_buf; if(dp==NULL) { fprintf(stderr,"opendir function is errorn"); exit(EXIT_FAILURE); } chdir(dir); while((d...


#include
#include
#include
#include
#include
#include
#include
void print_dir(char *dir,int depth)
{
DIR *dp=opendir(dir);
struct dirent *dirent;
struct stat stat_buf;

if(dp==NULL)
{
fprintf(stderr,"opendir function is errorn");
exit(EXIT_FAILURE);
}

chdir(dir);
while((dirent=readdir(dp))!=NULL)
{

lstat(dirent->d_name,&stat_buf);
if(S_ISDIR(stat_buf.st_mode))
{
if(strcmp(".",dirent->d_name)==0||
strcmp("..",dirent->d_name)==0)
continue;
printf("%*s%sn",depth," ",dirent->d_name);
print_dir(dirent->d_name,depth+4);

}
else
printf("%*s%sn",depth," ",dirent->d_name);
}
//chdir("..");如果去掉这里
closedir(dp);
}
int main(int argc,char *argv[])
{
if(argc==1)
print_dir(".",0);
else
{
while(--argc)
{
printf("%s:n",argv[argc]);
print_dir(argv[argc],0);
}
}
exit(EXIT_SUCCESS);
}

目录流指针作用的时候,当前目录一样要在它指向的目录下吗?

如果是如果我把那行返回上层目录去掉,程序第一次递归后进入一个子目录,第一次递归结束后,程序回不到上层目录,但是dp还是指向上层目录的啊···
我运行程序后···碰到第一个子目录他能读到子目录里面的文件,但之后的子目录就不在读到里面的文件,只能打印子目录本身。
这是我运行的结果:读一个目录流的时候是不是一定要再该目录下[图片]

这是code 这个目录下本来的文件:读一个目录流的时候是不是一定要再该目录下[图片]

比如里面的threestack 子目录 里面是有文件的··但是它只打印了目录本身

|
void print_dir(char *dir,int depth)
{
    DIR *dp=opendir(dir);
    struct dirent *dirent;
    struct stat stat_buf;
    char path[255] = {0};

    if(dp==NULL)
    {
        fprintf(stderr,"opendir function is errorn");
        exit(EXIT_FAILURE);
    }


    while((dirent=readdir(dp))!=NULL)
    {

        memset(path, 0, 255);
        if(dir[strlen(dir)-1] == '/')
                snprintf(path, 255, "%s", dir);
        else
                snprintf(path, 255, "%s/", dir);
        snprintf(path+strlen(path), 255, "%s", dirent->d_name);

        lstat(path,&stat_buf);
        if(S_ISDIR(stat_buf.st_mode))
        {
            if(strcmp(".",dirent->d_name)==0||
                strcmp("..",dirent->d_name)==0)
                continue;
            printf("Dir %*s%sn",depth," ",dirent->d_name);

            printf("path = %sn", path);
            print_dir(path,depth+4);


        }
        else
            printf("File %*s%sn",depth," ",dirent->d_name);
    }
    //chdir("..");......
    closedir(dp);
}

    
 
 
 
本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。














站内导航:


特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

©2012-2021,