(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博客