c++ 文件/文件夹操作

filesystem库是一个可移植的文件系统操作库,它在底层做了大量的工作,使用POSIX标准表示文件系统的路径,使C++具有了类似脚本语言的功能,可以跨平台操作目录、文件,写出通用的脚本程序。
1.path的构造函数可以接受C字符串和string,也可以是一个指定首末迭代器字符串序列区间。
2.filesystem提供了一系列的文件名(或目录)检查函数。
3.有丰富的函数用于获取文件名、目录名、判断文件属性等等。
4.filesystem库使用异常来处理文件操作时发生的错误。
5.filesystem库提供一个文件状态类file_status及一组相关函数,用于检查文件的各种属性,如是否存在、是否是目录、是否是符号链接等。
6.filesystem提供了少量的文件属性操作,如windows下的只读、归档等,Linux下的读写权限等。
7.文件操作,如创建目录、文件改名、文件删除、文件拷贝等等。
8.basic_directory_iterator提供了迭代一个目录下所有文件的功能。

//注意 /= 和 += 的区别, /= 表示追加下级目录, +=  仅仅是字符串的串接 
    path dir("C:\Windows");
    dir /= "System32";       //追加下级目录
    dir /= "services.exe";
    std::cout << dir << std::endl;
    std::cout << dir.string() << std::endl;            //转换成std::string 类型
    std::cout << dir.root_name()<< std::endl;          //盘符名:C:
    std::cout << dir.root_directory()<< std::endl;     //根目录:""
    std::cout << dir.root_path()<< std::endl;          //根路径:"C:"
    std::cout << dir.relative_path()<< std::endl;      // 相对路径:WindowsSystem32services.exe
    std::cout << dir.parent_path()<< std::endl;        //上级目录:C:WindowsSystem32
    std::cout << dir.filename()<< std::endl;           //文件名:services.exe
    std::cout << dir.stem()<< std::endl;               //不带扩展的文件名:services
    std::cout << dir.extension()<< std::endl;          //扩展名:.exe
//注意 /= 和 += 的区别, /= 表示追加下级目录, +=  仅仅是字符串的串接 
    path dir("C:\Windows");
    dir /= "System32";       //追加下级目录
    dir /= "services.exe";
    std::cout << dir << std::endl;
    std::cout << dir.string() << std::endl;            //转换成std::string 类型
    std::cout << dir.root_name()<< std::endl;          //盘符名:C:
    std::cout << dir.root_directory()<< std::endl;     //根目录:""
    std::cout << dir.root_path()<< std::endl;          //根路径:"C:"
    std::cout << dir.relative_path()<< std::endl;      // 相对路径:WindowsSystem32services.exe
    std::cout << dir.parent_path()<< std::endl;        //上级目录:C:WindowsSystem32
    std::cout << dir.filename()<< std::endl;           //文件名:services.exe
    std::cout << dir.stem()<< std::endl;               //不带扩展的文件名:services
    std::cout << dir.extension()<< std::endl;          //扩展名:.exe

用的qt,需要在qt pro文件中添加一些库,一开始会报错,网上查看,然后添加的库名字就没有问题了。。
XXX.pro

QT -= gui

CONFIG += c++11 console
CONFIG -= app_bundle

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += main.cpp

INCLUDEPATH += /usr/include


LIBS += -L/usr/lib

LIBS += -lboost_system 
        -lboost_filesystem

main.cpp

#include "boost/filesystem.hpp"
#include <iostream>
#include <string>
//using namespace std;


int main(int argc, char *argv[])
{
    boost::filesystem::path path("/media/data_2/everyday/0902/test2");   //初始化
    boost::filesystem::path old_cpath = boost::filesystem::current_path(); //取得当前程序所在文件夹
    boost::filesystem::path parent_path = old_cpath.parent_path();//取old_cpath的上一层父文件夹路径
    boost::filesystem::path file_path = old_cpath / "file"; //path支持重载/运算符
    if(boost::filesystem::exists(file_path))  //推断文件存在性
    {
        std::string strPath = file_path.string();
        int x = 1;
    }
    else
    {
        //文件夹不存在;
        boost::filesystem::create_directory(file_path);  //文件夹不存在。创建
    }
    bool bIsDirectory = boost::filesystem::is_directory(file_path); //推断file_path是否为文件夹
    boost::filesystem::recursive_directory_iterator beg_iter(file_path);
    boost::filesystem::recursive_directory_iterator end_iter;
    for (; beg_iter != end_iter; ++beg_iter)
    {
        if (boost::filesystem::is_directory(*beg_iter))
        {
            continue;
        }
        else
        {
            std::string strPath = beg_iter->path().string();  //遍历出来的文件名称
            int x=1;
        }
    }
    boost::filesystem::path new_file_path = file_path / "test.txt";
    if(boost::filesystem::is_regular_file(new_file_path))	//推断是否为普通文件
    {
        int sizefile = boost::filesystem::file_size(new_file_path);  //文件大小(字节)
        int x =1;
    }
    boost::filesystem::remove(new_file_path);//删除文件new_file_path

    return 1;
}

string curPath = “/home/test/cur/” ;
//定义一个可以递归的目录迭代器,用于遍历
boost::filesystem::recursive_directory_iterator itEnd;
for(boost::filesystem::recursive_directory_iterator itor( curPath.c_str() ); itor != itEnd ;++itor)
{
//itor->path().string()是目录下文件的路径
/*
*当curPath是相对路径时,itor->string()也是相对路径
*即当curPath = "../cur/",下面将输出"../cur/build.sh"
*/
//当curPath是绝对路径时,itor->string()也是绝对路径
string file = itor->path().string() ; // "/home/test/cur/build.sh"

//字符串和string类型作为参数,而提供的路径可以是相对路径,也可以是绝对路径。
boost::filesystem::path filePath(file);
//path的方法如filename()等,返回的对象仍是path,path的string()方法,获取string类型
//parent_path()获得的是当前文件的父路径
cout<<filePath.parent_path()<<endl;  // "/home/test/cur/"

//filename()获得的是文件名,含拓展名
cout<<filePath.filename()<<endl;  // "build.sh"
cout<<filePath.filename().string()<<endl;

//stem()获得的是文件的净文件名,即不含拓展名
cout<<filePath.stem()<<endl; // "build"

//拓展名(是".sh"而不是"sh")
cout<<filePath.extension()<<endl; // ".sh"

//获得文件的大小,单位为字节
int nFileSize = boost::filesystem::file_size(filePath);

//最后一次修改文件的时间
//last_write_time()返回的是最后一次文件修改的绝对秒数
//last_write_time(filePath,time(NULL))还可以修改文件的最后修改时间,相当于Linux中命令的touch
if(filePath.last_write_time() - time(NULL) > 5)
{
    /*
     *在工程实践中,当需要不断的扫目录,而目录又会不断的加入新文件时,
     *借助last_write_time()可以判断新入文件的完整性,以避免处理未写完的文件
     */
}

//判断文件的状态信息
if(boost::filesystem::is_regular_file(file))
{
    //is_regular_file(file)普通文件
    //is_directory(file)目录文件,如当遍历到"/home/test/cur/src/"时,这就是一个目录文件
    //is_symlink(file)链接文件
    ...
}

//更改拓展名
boost::filesystem::path tmpPath = filePath;
//假设遍历到了cpp文件,想看下对应的.o文件是否存在
tmpPath.replace_extension(".o");
//判断文件是否存在
if( boost::filesystem::exists( tmpPath.string() ) )

//删除文件
//remove只能删除普通文件,而不能删除目录
boost::filesystem::remove(tmpPath.string());
//remove_all则提供了递归删除的功能,可以删除目录
boost::filesystem::remove_all(tmpPath.string());

//移动文件 & 拷贝文件
//srcPath原路径,srcPath的类型为string
//destPath目标路径,destPath的类型为string
boost::filesystem::rename(srcPath , destPath);
boost::filesystem::copy_file(srcPath , destPath);
//拷贝目录
boost::filesystem::copy_files("/home/test","/dev/shm")

}

boost::filesystem还可以创建目录:
if( !boost::filesystem::exists( strFilePath ) )
{
boost::filesystem::create_directories(strFilePath)
}


我主要是用在判断文件是否存在,不存在就创建

#include "boost/filesystem.hpp"
#include <iostream>
#include <string>
//using namespace std;


int main(int argc, char *argv[])
{
    std::string file_path = "/media/data_2/everyday/0902/test1";
    if(boost::filesystem::exists(file_path))  //推断文件存在性
    {
        std::cout<<"file is exist"<<std::endl;
    }
    else
    {
        //文件夹不存在;
        boost::filesystem::create_directory(file_path);  //文件夹不存在。创建
    }

    std::string srcPath = "/media/data_2/everyday/0902/test.txt";
    std::string destPath = "/media/data_2/everyday/0902/test1/1112.txt"; //需要具体到文件名,要不然报错
    boost::filesystem::copy_file(srcPath , destPath);

    //获取文件名
    std::string srcPath = "/media/data_2/everyday/0902/test.txt";
    boost::filesystem::path path_file(srcPath);
    std::string file_name = path_file.filename().string();
    std::cout<<file_name<<std::endl;// test.txt

    return 1;
}

boost::filesystem获取目录下的所有文件名

#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
 
int get_filenames(const std::string& dir, std::vector<std::string>& filenames)
{
	fs::path path(dir);
	if (!fs::exists(path))
	{
		return -1;
	}
 
	fs::directory_iterator end_iter;
	for (fs::directory_iterator iter(path); iter!=end_iter; ++iter)
	{
		if (fs::is_regular_file(iter->status()))
		{
			filenames.push_back(iter->path().string());
		}
 
		if (fs::is_directory(iter->status()))
		{
			get_filenames(iter->path().string(), filenames);
		}
	}
 
	return filenames.size();
}
原文地址:https://www.cnblogs.com/yanghailin/p/11445770.html