日期:2014-05-16  浏览次数:20739 次

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

#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<dirent.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
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 error\n");
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%s\n",depth," ",dirent->d_name);
print_dir(dirent->d_name,depth+4);

}
else
printf("%*s%s\n",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 error\n");
        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_nam