遍历打印目录下的文件——递归

(1)假设有:TEXT/hello/b/c,TEXT/hello/a。a、c是普通文件,b是目录文件。

(2)代码:

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<dirent.h>
#include<fcntl.h>
#include<string.h>

void dir_oder(char *path)
{
        DIR *dp;
        struct dirent *pdir;
        char pathname[128];
//      char *pathname = NULL;
        dp = opendir(path);
        if(dp == NULL)
        {
                perror("open failed");
                return ;
        }
        while(pdir = readdir(dp))
        {
                if(strncmp(pdir->d_name,".",1) == 0)
                continue;
                printf("name:%s  ",pdir->d_name);
                if(pdir->d_type == DT_DIR)
                {
                        sprintf(pathname,"%s/%s",path,pdir->d_name);
                        dir_oder(pathname);
                }
        }
        printf("\n");
        closedir(dp);
}

int main()
{
        int ret;
        if(access("./hello",F_OK) != 0)
        {
                printf("file make");
                ret = mkdir("./hello",0777);
        if(ret < 0)
        {
                perror("make failed");
                return -1;
        }
        }

        dir_oder("./hello");
        return 0;
}

(3)注意事项:使用sprintf时,第一个参数直接定于指针出错,定义数组才正确。原因可能是,要求指针指向的字符串缓冲区必须是有效可写地址。而且,sprintf()函数是不安全的。

(4)参考文献:c语言中sprintf()使用,第一个参数char*传入说明_sprintf第一个参数_卫东131的博客-CSDN博客

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值