当前位置: 技术问答>linux和unix
在Linux如何得到一个文件夹下的所有文件
来源: 互联网 发布时间:2015-08-25
本文导语: 如我已知一个目录,但不知道里面有多少文件 希望得到该目录下的所有文件 最好有示例代码! 多谢!! | 例子: #include #include #include #include int ...
如我已知一个目录,但不知道里面有多少文件
希望得到该目录下的所有文件
最好有示例代码!
多谢!!
希望得到该目录下的所有文件
最好有示例代码!
多谢!!
|
例子:
#include
#include
#include
#include
int
main (void)
{
DIR *dp;
struct dirent *ep;
dp = opendir ("./");
if (dp != NULL)
{
while (ep = readdir (dp))
puts (ep->d_name);
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
return 0;
}
#include
#include
#include
#include
int
main (void)
{
DIR *dp;
struct dirent *ep;
dp = opendir ("./");
if (dp != NULL)
{
while (ep = readdir (dp))
puts (ep->d_name);
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
return 0;
}
|
我也貼一個,以前為動態目錄樹寫的一個code,結果包括當前目錄下所有文件名,所在層數,子目錄含有幾個file gcc編譯通過,呵呵...
#include
#include
#include
#include
#include
#include
void printdir(char *dir, int *depth, FILE * filefd)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
FILE *fp;
int num = 0;
fp = filefd;
if((dp = opendir(dir)) == NULL)
{
fprintf(stderr,"cannot open directory:%sn",dir);
return;
}
chdir(dir);
while((entry = readdir(dp)) != NULL)
{
lstat(entry->d_name,&statbuf);
num = statbuf.st_nlink - 2;
if(S_ISDIR(statbuf.st_mode))
{
if(strcmp(".",entry->d_name) == 0 || strcmp("..",entry->d_name) == 0)
continue;
(*depth)++;
fprintf(fp,"%s %d %dn",entry->d_name,*depth,num);
printdir(entry->d_name,depth, fp);
}
}
chdir("..");
(*depth) --;
closedir(dp);
}
int main(int argc, char* argv[])
{
char *topdir = ".";
FILE * filefd;
int depth = 0;
if(argc >= 2)
topdir=argv[1];
filefd=fopen("/tmp/folder_info","w");
printdir(topdir,&depth,filefd);
fclose(filefd);
exit(0);
}
#include
#include
#include
#include
#include
#include
void printdir(char *dir, int *depth, FILE * filefd)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
FILE *fp;
int num = 0;
fp = filefd;
if((dp = opendir(dir)) == NULL)
{
fprintf(stderr,"cannot open directory:%sn",dir);
return;
}
chdir(dir);
while((entry = readdir(dp)) != NULL)
{
lstat(entry->d_name,&statbuf);
num = statbuf.st_nlink - 2;
if(S_ISDIR(statbuf.st_mode))
{
if(strcmp(".",entry->d_name) == 0 || strcmp("..",entry->d_name) == 0)
continue;
(*depth)++;
fprintf(fp,"%s %d %dn",entry->d_name,*depth,num);
printdir(entry->d_name,depth, fp);
}
}
chdir("..");
(*depth) --;
closedir(dp);
}
int main(int argc, char* argv[])
{
char *topdir = ".";
FILE * filefd;
int depth = 0;
if(argc >= 2)
topdir=argv[1];
filefd=fopen("/tmp/folder_info","w");
printdir(topdir,&depth,filefd);
fclose(filefd);
exit(0);
}