c++17之后c++就已经支持文件系统操作了,用来解析目录方便很多。这里是自己写的一个例子,如果是gcc8,编译时需加-lstdc++fs。gcc9应该不用加了。但是都要开启 -std=c++17 。
代码
#include
#include
#include int main()
{
namespace fs = std::filesystem;
auto picpath = fs::path("/data/newface/yll.jpg");
std::string stem = picpath.stem();
std::string extension = picpath.extension();
printf("stem:[%s], extension[%s]\n", stem.c_str(), extension.c_str());
//截取文件名和扩展名 auto parent_path = picpath.parent_path().string();
//文件的上层目录
auto filename = picpath.filename().string();
//文件名
auto new_path = picpath.parent_path().append("111.jpg");
printf("parent_path[%s], filename[%s], new_path[%s]\n", parent_path.c_str(), filename.c_str(), new_path.string().c_str());
bool has_pic = fs::exists(picpath) && fs::is_regular_file(picpath);
//判断是否存在并且是普通文件
if (has_pic)
{
fs::copy_file(picpath, new_path);
//复制一份
fs::remove(picpath);
//删除文件
} return 0;
}
编译命令:
gcc main.cpp -std=c++17 -lstdc++fs-lstdc++
【c++|c++17操作文件并解析目录】执行输出:
stem:[yll], extension[.jpg]
parent_path[/data/newface], filename[yll.jpg], new_path[/data/newface/111.jpg]
推荐阅读
- YY|【C语言】通讯录《静态内存版本》
- python|python程序向企业微信机器人发送消息
- java|JAVA计算机毕业设计大学生网络创业就业管理系统Mybatis+源码+数据库+lw文档+系统+调试部署
- java|docker-compose安装教程
- 机器学习|神经网络(一)基本概念
- python|python实现字符串数据类型转List列表数据类型
- java|解决错误(org.apache.ibatis.binding.BindingException)
- 面试|线程池异常如何处理你都了解吗()
- java初阶|Java-异常处理大全(万字宝典)