c++ 文件/文件夹操作

用的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;
}

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

#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);  //文件夹不存在。创建
    }
    return 1;
}

猜你喜欢

转载自www.cnblogs.com/yanghailin/p/11445770.html