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;      // 相對路徑:Windows\System32\services.exe
    std::cout << dir.parent_path()<< std::endl;        //上級目錄:C:\Windows\System32
    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;      // 相對路徑:Windows\System32\services.exe
    std::cout << dir.parent_path()<< std::endl;        //上級目錄:C:\Windows\System32
    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();
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM