C++,文件,文件夹操作,创建、删除、检测

 推荐  filesystem ,特别好用,除了新建、删除、复制、移动文件夹,还支持磁盘空间检测,权限检测,路径处理。

 

一、使用系统库

// 检测文件,检测文件夹
/* windows
* 头文件:io.h
* 函数:int access(const char* _Filename, int _AccessMode);
* 
* _AccessMode参数说明: 00表示只判断是否存在,02表示文件是否可执行, 04表示文件是否可写,06表示文件是否可读
*                     有访问权限返回0,否则返回-1
*/
/* Linux
* 头文件:unistd.h
* 函数:int access(const char* _Filename, int _AccessMode);
*
* _AccessMode参数说明: 00表示只判断是否存在,02表示文件是否可执行, 04表示文件是否可写,06表示文件是否可读
*                     有访问权限返回0,否则返回-1
*/


// 创建文件夹
/* windows
* 头文件:direct.h
* 函数:int mkdir(const char* _Path);
* 返回值:0(成功),-1(失败)
*/
/* Linux
* 头文件:sys/types.h, sys/stat.h
* 函数:int mkdir(const char* _Path, mode_t mode);
* 返回值:0(成功),-1(失败)
*/


// 删除文件夹
/* windows
* 头文件:direct.h
* 函数:int rmdir(const char* _Path);
* 返回值:0(成功),-1(失败)
*/
/* Linux
* 头文件:sys/types.h, sys/stat.h
* 函数:int rmdir(const char* _Path);
* 返回值:0(成功),-1(失败)
*/

 

 

二、使用C++库

#include <iostream>
#include <filesystem>
using namespace std;

int main()
{
    cout << "C++17 Filesystem" << endl;

    // 创建文件夹
    bool ret = std::filesystem::create_directory("C:\\t1");
    if (ret) 
    {
        cout << "创建文件夹成功" << endl;
    }

    // 复制文件
    std::filesystem::copy("C:\\t1\\1.txt", "C:\\t1\\2.txt");

    // 删除文件,删除文件夹
    ret = std::filesystem::remove("C:\\t1\\2.txt");
    if (ret)
    {
        cout << "删除文件成功" << endl;
    }


    // =========  路径处理 ==========
    // 路径拼接
    std::filesystem::path base_path = "C:\\t1";
    std::filesystem::path file_name = "a.txt";
    std::filesystem::path full_path = base_path / file_name;
    cout << "拼接路径:" << full_path << endl;

    // 路径解析
    cout << "文件夹路径:" << full_path.parent_path() << endl;
    cout << "完整文件名:" << full_path.filename() << endl;
    cout << "文件名(不带后缀):" << full_path.stem() << endl;
    cout << "文件名后缀:" << full_path.extension() << endl;


    return 0;
}

 

 

 

 

 

 

相关链接:https://blog.csdn.net/qq_21438461/article/details/132644824

 

posted @ 2024-04-12 17:48  十一的杂文录  阅读(31)  评论(0编辑  收藏  举报