Linux C++ 访问子目录以及里面的文件

时间:2022-09-14 10:56:29
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h> using namespace std; #define dmax(a,b) (((a) > (b)) ? (a) : (b))
#define dmin(a,b) (((a) < (b)) ? (a) : (b)) //获取特定格式的文件名
int readFileList(std::vector<string> &filelist, const char *basePath, string format)
{
DIR *dir;
struct dirent *ptr;
char base[]; if ((dir=opendir(basePath)) == NULL)
{
perror("Open dir error...");
exit();
} while ((ptr=readdir(dir)) != NULL)
{
if(strcmp(ptr->d_name,".")== || strcmp(ptr->d_name,"..")==) ///current dir OR parrent dir
continue;
else if(ptr->d_type == ) //file
{
//printf("d_name:%s/%s\n",basePath,ptr->d_name);
string temp = ptr->d_name;
//cout << temp << endl;
string sub = temp.substr(temp.length() - , temp.length()-);
//cout << sub << endl;
if(sub == format)
{
string path = basePath;
path += "/";
path += ptr->d_name;
filelist.push_back(path);
}
}
else if(ptr->d_type == ) ///link file
{
//printf("d_name:%s/%s\n",basePath,ptr->d_name);
}
else if(ptr->d_type == ) ///dir
{
memset(base,'\0',sizeof(base));
strcpy(base,basePath);
strcat(base,"/");
strcat(base,ptr->d_name);
readFileList(filelist, base, format);
}
}
closedir(dir);
return ;
} //找出目录中所有子目录
int findAllSubDir(std::vector<string> &filelist, const char *basePath)
{
DIR *dir;
struct dirent *ptr;
char base[]; if ((dir=opendir(basePath)) == NULL)
{
perror("Open dir error...");
exit();
} while ((ptr=readdir(dir)) != NULL)
{
if(strcmp(ptr->d_name,".")== || strcmp(ptr->d_name,"..")==) ///current dir OR parrent dir
continue;
else if(ptr->d_type == ) //file
{
// //printf("d_name:%s/%s\n",basePath,ptr->d_name);
// string temp = ptr->d_name;
// //cout << temp << endl;
// string sub = temp.substr(temp.length() - 4, temp.length()-1);
// //cout << sub << endl;
// if(sub == format)
// {
// string path = basePath;
// path += "/";
// path += ptr->d_name;
// filelist.push_back(path);
// }
}
else if(ptr->d_type == ) ///link file
{
//printf("d_name:%s/%s\n",basePath,ptr->d_name);
}
else if(ptr->d_type == ) ///dir
{
memset(base,'\0',sizeof(base));
strcpy(base,basePath);
strcat(base,"/");
strcat(base,ptr->d_name);
filelist.push_back(ptr->d_name);
findAllSubDir(filelist, base);
}
}
closedir(dir);
return ;
} void findDir(string src, string &facefolder, string &facenameindex, string filePath)
{
int begin = src.find(filePath) + filePath.size() + ;
int end = ;
for (int i = src.size() - ; i >= ; --i)
{
//cout << src[i] << endl;
if (src[i] == '/')
{
end = i;
break;
}
}
//cout << begin << endl;
//cout << end << endl;
facefolder = src.substr(begin, end - - begin + );
facenameindex = src.substr(end + , src.size() - - (end + ) + );
} void GetStringFileName(const string &filePath, string &filename, string &fileformat)
{
int fileformat_begin = ;
int fileformat_end = filePath.length() - ;
int filename_begin = ;
int filename_end = filePath.length() - ;
for (int i = filePath.length() - ; i >= ; --i)
{
//cout << filePath[i] << endl;
if (filePath[i] == '.')
{
fileformat_begin = i + ;
filename_end = i - ;
} if (filePath[i] == '/')
{
filename_begin = i + ;
break;
}
}
// cout << filename_begin << endl;
// cout << filename_end << endl;
filename = filePath.substr(filename_begin, filename_end - filename_begin + );
fileformat = filePath.substr(fileformat_begin, fileformat_end - fileformat_begin + );
} void StringSplit(const string &src, const char splitchar, vector<string> &dst)
{
int begin = ;
int end = ;
int i = ;
for (i = ; i < src.length(); ++i)
{
if(src[i] == splitchar)
{
end = i - ;
dst.push_back(src.substr(begin, end - begin + ));
begin = i + ;
end = begin;
}
} //last
if(i > end)
{
end = i - ;
}
dst.push_back(src.substr(begin, end - begin + ));
} //遍历一个目录,找出其中某一后缀的所有文件
void sence0()
{
// Loop over all the images provided on the command line.
std::vector<string> srcfiles;
string srcpath = "./src/1";
string srcformat = ".txt";
string outputformat = ".png";
printf("the current dir is : %s\n", srcpath.c_str());
readFileList(srcfiles, srcpath.c_str(), srcformat);
string dstpath = "./src/3";
printf("the dst dir is : %s\n", dstpath.c_str());
if (access(dstpath.c_str(), ) == -)
{
int flag=mkdir(dstpath.c_str(), );
} std::vector<string> dstfiles(srcfiles.size());
for (int i = ; i < srcfiles.size(); ++i)
{
/* code */
cout << srcfiles[i] << endl;
string filename;
string fileformat;
GetStringFileName(srcfiles[i], filename, fileformat);
string dstfile = dstpath + "/" + filename + "." + fileformat;
dstfiles[i] = dstfile;
cout << dstfiles[i] << endl;
}
} //建立多级目录,包括子目录, 并依次处理文件,适用于小文件
void sence1()
{
// Loop over all the images provided on the command line.
std::vector<string> files;
string filePath = "./lfw_small_raw";
string format = ".jpg";
string outputformat = ".png";
printf("the current dir is : %s\n", filePath.c_str());
readFileList(files, filePath.c_str(), format);
string dstpath = "./lfw_small_convert";
printf("the dst dir is : %s\n", dstpath.c_str());
if (access(dstpath.c_str(), ) == -)
{
int flag=mkdir(dstpath.c_str(), );
} std::vector<string> alignimg(files.size());
for (int i = ; i < files.size(); ++i)
{
/* code */
cout << files[i] << endl;
string facefolder;
string facenameindex;
findDir(files[i], facefolder, facenameindex, filePath);
facenameindex = facenameindex.substr(, facenameindex.size() - );
facenameindex += outputformat;
//cout << facefolder << endl;
//cout << facenameindex << endl;
string newfacefolder = dstpath + "/" + facefolder;
if (access(newfacefolder.c_str(), ) == -)
{
int flag=mkdir(newfacefolder.c_str(), );
}
alignimg[i] = newfacefolder + "/" + facenameindex;
cout << alignimg[i] << endl;
}
} //依次遍历文件夹中的每一个目录,遇到一个目录新建一个目录,然后遍历该目录的文件
void sence2()
{
// Loop over all the images provided on the command line.
std::vector<string> sudDirfiles;
string srcpath = "./lfw_small_raw";
string dstpath = "./lfw_small_convert"; //如果目录存在就删除目录
if (access(dstpath.c_str(), ) == )
{
cout << "remove " << dstpath << endl;
int flag = rmdir(dstpath.c_str());
} //如果目录不存在就新建
if (access(dstpath.c_str(), ) == -)
{ cout << "mkdir " << dstpath << endl;
int flag=mkdir(dstpath.c_str(), );
} findAllSubDir(sudDirfiles, srcpath.c_str());
for (int i = ; i < sudDirfiles.size(); ++i)
{
//cout << sudDirfiles[i] << endl;
//遍历当前子目录中所有文件
std::vector<string> srcfiles;
string srcSudDir = srcpath + "/" + sudDirfiles[i];
string srcformat = ".jpg";
printf("the current subdir is : %s\n", srcSudDir.c_str()); string dstSudDir = dstpath + "/" + sudDirfiles[i];
//建立目标子目录
if (access(dstSudDir.c_str(), ) == -)
{
cout << "mkdir " << dstSudDir << endl;
int flag=mkdir(dstSudDir.c_str(), );
}
printf("the current subdir is : %s\n", dstSudDir.c_str()); readFileList(srcfiles, srcSudDir.c_str(), srcformat);
for (int j = ; j < srcfiles.size(); ++j)
{
cout << srcfiles[j] << endl;
string filename;
string fileformat;
GetStringFileName(srcfiles[j], filename, fileformat);
string dstfile = dstSudDir + "/" + filename + "." + fileformat;
cout << dstfile << endl;
}
}
} int main()
{
sence2();
// string filePath = "./lfw_small_raw/Aaron_Eckhart";
// std::vector<string> split;
// StringSplit(filePath, '/', split);
// string curSubDir = split[split.size() - 1];
// cout << curSubDir << endl;
// for (int i = 0; i < split.size(); ++i)
// {
// cout << split[i] << endl;
// } // string filename;
// string fileformat;
// GetStringFileName(filePath, filename, fileformat);
// //cout << filePath.substr(2, 3) << endl;
// cout << filePath << endl;
// cout << filename << endl;
// cout << fileformat << endl;
return ;
}

Linux C++ 访问子目录以及里面的文件的更多相关文章

  1. Linux 终端访问 FTP 及 上传下载 文件

    今天同事问我一个问题,在Linux 下访问FTP,并将文件上传上去. 我之前一直是用WinSCP工具的. 先将文件从linux copy到windows下,然后在传到ftp上.google 一下. 方 ...

  2. Linux怎样访问Windows共享文件和文件夹

    常常使用Windows的人可能会发现,Windows计算机之前共享资料非常方便,但是有时候想玩玩Linux的时候,如Fedora.Ubuntu.CentOS等,该怎样才能访问Windows计算机上的文 ...

  3. Linux 终端访问 FTP 及 上传下载 文件&lbrack;转&rsqb;

    1.      Linux 终端连接FTP [oracle@Dave ~]$ ftp 10.85.7.97 Connected to 10.85.7.97. 220 Serv-U FTP Server ...

  4. linux下删除目录及其子目录下某种类型文件

    Linux下,如果想要删除目录及其子目录下某种类型文件,比如说所有的txt文件,则可以使用下面的命令: find . -name "*.txt" -type f -print -e ...

  5. win下gvim或者linux下的vim安装vundle都适用的配置文件 - 在当前目录及其子目录下&ast;&ast;&comma; 的所有文件&ast; 中&comma; 搜索当前光标所在的单词

    gvim下的普通配置: if v:lang =~ "utf8$" || v:lang =~ "UTF-8$" set fileencodings=utf-8,g ...

  6. Linux查看当前目录下所有子目录是否包含某个文件

    在Linux下,当需要找某个文件但又不知道这个文件在哪个具体的目录下,这时可以使用全目录查找 使用find命令: find . -type f -name "job_21_output*&q ...

  7. linux上搭建nginx&plus;ftp,实现文件的上传与访问

    ftp服务器搭建 1.新建用户ftpuser并指定主目录为/home/ftpuser (注意:这个目录是后面存储和读取文件的目录) <!--创建用户并指定主目录--> useradd -d ...

  8. Linux centos7 VMware Apache访问日志不记录静态文件、访问日志切割、静态元素过期时间

    一.Apache访问日志不记录静态文件 网站大多元素为静态文件,如图片.css.js等,这些元素可以不用记录 vim /usr/local/apache2.4/conf/extra/httpd-vho ...

  9. linux复制指定目录下的全部文件到另一个目录中

    linux复制指定目录下的全部文件到另一个目录中复制指定目录下的全部文件到另一个目录中文件及目录的复制是经常要用到的.linux下进行复制的命令为cp.假设复制源目录 为 dir1 ,目标目录为dir ...

随机推荐

  1. 用css实现网站切角效果 使用css3属性&colon;渐变

     都是大量的练习,老师练习乒乓球花了大量时间,十万次一个动作的重复,高中班主任说过,世上没有天才,只是重复的次数多了,自然被认作了天才,小小班的学生之所以厉害是因为他们重复一个知识点次数多,所以没有一 ...

  2. SQL Server 身份验证 登陆

    当遇到错误 检查SQL是否启动 SQL Server (MSSQLSERVER)在 打开 SQL Server 配置管理器 SQL Server (MSSQLSERVER) 鼠标右键->启动 再 ...

  3. UINavigationController具体解释&lpar;二&rpar;

    @UINavigationBar-----(是一个View)基本介绍 1.导航栏,和导航控制器一样,是一个容器用来显示提供的其它对象的内容 2.导航栏显示的内容,通过设置UINavigationIte ...

  4. python 初学习 模拟用户登录

    #!/usr/bin/env python#coding:utf-8''' 2017年8月19日 模拟用户登录,userfile 文件保存字典 用户名,和密码 sorryname 文件保存字典 登录过 ...

  5. Maven Scope 依赖范围

    Maven依赖范围就是用来控制依赖与这三种classpath(编译classpath.测试classpath.运行classpath)的关系,Maven有以下几种依赖范围: ·compile:编译依赖 ...

  6. 内存溢出OOM

    如何避免OOM 异常? 想要避免OOM 异常首先我们要知道什么情况下会导致OOM 异常. 1.图片过大导致OOM Android 中用bitmap 时很容易内存溢出,比如报如下错误:Java.lang ...

  7. spark大批量读取Hbase时出现java&period;lang&period;OutOfMemoryError&colon; unable to create new native thread

    这个问题我去网上搜索了一下,发现了很多的解决方案都是增加的nproc数量,即用户最大线程数的数量,但我修改了并没有解决问题,最终是通过修改hadoop集群的最大线程数解决问题的. 并且网络上的回答多数 ...

  8. 使用Chrome开发者工具远程调试原生Android上的H5页面

    Android4.4(KitKat)开始,使用Chrome开发者工具可以帮助我们在原生的Android应用中远程调试WebView网页内容.具体步骤如下: (1)设置Webview调试模式 可以在Ac ...

  9. 解决UnicodeEncodeError。python的docker镜像增加locale 中文支持

    用pandas的pd.read_excel()打开中文名的xlsx,报错,本来以为是xlrd的问题后来发现,是open()函数就报错: “UnicodeEncodeError: 'ascii' cod ...

  10. java理论学时第七节。课后作业。

    对AboutException.java的理解.在try中如果发出某类系统识别的错误,会以throw的形式抛出,在catch中可以将其截获,不显示在前端,可以选择执行别的代码. ArrayIndexO ...