linux中的读目录,在linux中读取目录内容
我們如何在
Linux中使用C語言讀取目錄的內容(子目錄和文件名).
這是一個遞歸程序,以遞歸方式打印所有子目錄和文件的名稱.
用法:./ a.out路徑名
不檢查作為命令行參數提供的初始路徑名的錯誤條件.
基本代碼流程:
讀取當前目錄中的所有條目.
如果是目錄名,則將其名稱添加到路徑名中,并以遞歸方式調用函數.
否則打印文件的名稱.
有關特定函數的詳細信息可以在dmuir指出的各個手冊頁中引用:
#include
#include
#include
#include
int read(char *pth)
{
char path[1000];
strcpy(path,pth);
DIR *dp;
struct dirent *files;
/*structure for storing inode numbers and files in dir
struct dirent
{
ino_t d_ino;
char d_name[NAME_MAX+1]
}
*/
if((dp=opendir(path))==NULL)
perror("dir\n");
char newp[1000];
struct stat buf;
while((files=readdir(dp))!=NULL)
{
if(!strcmp(files->d_name,".") || !strcmp(files->d_name,".."))
continue;
strcpy(newp,path);
strcat(newp,"/");
strcat(newp,files->d_name);
printf("%s\n",newp);
//stat function return a structure of information about the file
if(stat(newp,&buf)==-1)
perror("stat");
if(S_ISDIR(buf.st_mode))// if directory, then add a "/" to current path
{
strcat(path,"/");
strcat(path,files->d_name);
read(path);
strcpy(path,pth);
}
}
}
int main(int argc,char *argv[])
{
read(argv[1]);
}
總結
以上是生活随笔為你收集整理的linux中的读目录,在linux中读取目录内容的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux设置脚本开机启动centos7
- 下一篇: linux多线程编写哲学家,Linux系