方法1:
/Article/ef431d9b-68b3-419f-9f85-1fb9279f904a.html
//ListFile.cpp
#include<stdio.h>
#include<dirent.h>
#include<sys/types.h>
intmain(intargc,char*argv[]){
if(2!=argc){
printf("Usage:ListFileSourceFolder");
return1;
}
DIR*pDir=NULL;
structdirent*ent=NULL;
pDir=opendir(argv[1]);
if(NULL==pDir){
printf("Sourcefoldernotexists!");return1;
}
while(NULL!=(ent=readdir(pDir))){
printf("%s",ent->d_name);
}
closedir(pDir);
pDir=NULL;
方 //ListFile.cpp
#include<stdio.h>
#include<dirent.h>
#include<sys/types.h>
intmain(intargc,char*argv[]){
if(2!=argc){
printf("Usage:ListFileSourceFolder");
return1;
}
DIR*pDir=NULL;
structdirent*ent=NULL;
pDir=opendir(argv[1]);
if(NULL==pDir){
printf("Sourcefoldernotexists!");return1;
}
while(NULL!=(ent=readdir(pDir))){
printf("%s",ent->d_name);
}
closedir(pDir);
pDir=NULL; 法2:
/t/1221/16/4472968.html
试试下面的代码,我是在redhat上编译运行的。
//g++-oread_dirread_dir.cpp
//用于列出参数目录下的文件
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<dirent.h>
intmain(intargc,char*argv[])
{
DIR*dp;
structdirent*dirp;
if(argc!=2)
{
printf("notenougharguments!exit!\n");
exit(0);
}
if((dp=opendir(argv[1]))==NULL)
{
printf("can'topen%s!\n",argv[1]);
exit(0);
}
while((dirp=readdir(dp))!=NULL)
printf("%s\n",dirp->d_name);
closedir(dp);
}
方法3
#include<stdio.h>
#include<dirent.h>
#include<sys/types.h>
#include<sys/stat.h>
voiddir_scan(char*path,char*file);
intcount=0;
intmain(intargc,char*argv[])
{
structstats;
if(argc!=2){
printf("onedirectionrequried\n");
exit(1);
}
if(lstat(argv[1],&s)<0){
printf("lstaterror\n");
exit(2);
}
if(!S_ISDIR(s.st_mode)){
printf("%snotdirectionname\n",argv[1]);
exit(3);
}
dir_scan("",argv[1]);
printf("total:%dfiles\n",count);
exit(0);
}
voiddir_scan(char*path,cha日*file)
{
structstats;
DIR*dir;
structdirent*dt;
chardirname[50];
memset(dirname,0,50*sizeof(char));
strcpy(dirname,path);
if(lstat(file,&s)<0){
printf("lstaterror\n");
}
if(S_ISDIR(s.st_mode)){
strcpy(dirname+strlen(dirname),file);
strcpy(dirname+strlen(dirname),"/");
if((dir=opendir(file))==NULL){
printf("opendir%s/%serror\n");
exit(4);
}
if(chdir(file)<0){
printf("chdirerror\n");
exit(5);
}
while((dt=readdir(dir))!=NULL){
if(dt->d_name[0]=='.'){
continue;
}
dir_scan(dirname,dt->d_name);
}
if(chdir("..")<0){
printf("chdirerror\n");
exit(6);
}
}else{
printf("%s%s\n",dirname,file);
count++;
}
}