先上代码有空再解释
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<dirent.h>
#include<stdio.h>
#include<unistd.h>
#include<errno.h>
#include<string>
#include<string.h>
#include<vector>
using namespace std;
void my_create();
vector<string> getFiles(string cate_dir);
int main()
{
string cate_dir="/media/ubuntu/";
string dir;
vector<string> files=getFiles(cate_dir);
int num_file = 0;
if (!files.empty())
{
num_file=files.size();
dir = cate_dir+files.front()+"/image/";
printf("the number of files is : %d\n the final path is:%s\n",num_file,dir.c_str());
}
return 0;
}
void my_create()
{
int fd;
if((fd=open("text.txt",O_CREAT|O_EXCL,S_IRUSR|S_IWUSR))==-1)
{
perror("open");
}else
{
printf("create file success\n");
}
close(fd);
}
vector<string> getFiles(string cate_dir)
{
vector<string> files;//存放文件名
DIR *dir;
struct dirent *ptr;
char base[1000];
if ((dir=opendir(cate_dir.c_str())) == NULL)
{
perror("Open dir error...");
//exit(1);
}
while ((ptr=readdir(dir)) != NULL)
{
if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0) ///current dir OR parrent dir
{
continue;
}
else if (ptr->d_type == 8) ///file
{
printf("d_name:%s%s\n",cate_dir.c_str(),ptr->d_name);
//files.push_back(ptr->d_name);
continue;
}
else if(ptr->d_type == 10) ///link file
{
printf("d_name:%s/%s\n",cate_dir.c_str(),ptr->d_name);
continue;
}
else if(ptr->d_type == 4) ///dir
{
files.push_back(ptr->d_name);
printf("d_name:%s%s\n",cate_dir.c_str(),ptr->d_name);
}
}
closedir(dir);
return files;
}