c++17 std::filesystem

#include <iostream>
//c++17
#include<filesystem>
using namespace std;
/*
这个filesystem基本是在msvc下测试
g++此时还把filesystem放在expermental里,cppref上的测试代码也报错,无语
*/
int main()
{
    //https://en.cppreference.com/w/cpp/filesystem/path
    //
    //在windows上,理论上是使用反斜杠的,但是其实也会帮你转化正斜杠
    //
    //获得当前程序所在目录
    //
    filesystem::path current_path("./");
    filesystem::path canonical_path;

    //获得绝对路径
    //"C:\\Users\\sbb\\source\\repos\\c++io\\c++io17"
    cout << (canonical_path = filesystem::canonical(current_path)) << '\n';

    cout << (canonical_path/"c++io17.cpp").filename() << endl;
    cout << (canonical_path / "c++io17.cpp").stem() << endl;
    cout << (canonical_path / "c++io17.cpp").extension() << endl;

    //内部自带子路径,也就是把全路径分割成各个子路径
    for(auto child_path : (canonical_path / "c++io17.cpp"))
    {
        cout << child_path;
    }

    cout << '\n';

    //"C:\\Users\\sbb\\AppData\\Local\\Temp\\"
    cout << filesystem::temp_directory_path() << '\n';
    
    //创建一个在当前exe目录下名为abc的文件夹
    auto d1 = current_path / "abc";
    cout << filesystem::create_directories(d1) << '\n';

    //可以判断一个文件或路径是否存在
    cout << filesystem::exists(d1) << '\n';

    //获得文件的大小
    cout << filesystem::file_size(current_path / "c++io17.cpp") << endl;
    
    //更改文件的属性,比如只读
    try
    {
        filesystem::permissions(current_path / "test",filesystem::perms::group_read);
    }
    catch (...)
    {
        cout << "no a file named 'test'!\n";
    }

    //remove       removes a file or empty directory
    //remove_all   removes a file or directory and all its contents, recursively
    cout << filesystem::remove_all(d1) << '\n';

    //将'test'文件命名为'aa'
    try
    {
        filesystem::rename(current_path / "test","aa");
    }
    catch(...)
    {
        cout << "no a file named 'test'!\n";
    }

    try
    {
        filesystem::resize_file(current_path / "aa",0x2000);
    }
    catch (...)
    {
        cout << "file probably be non-write!\n";
    }


    //checks whether the given path refers to an empty file or directory
    //如果文件/文件夹不存在,引发异常
    cout << filesystem::is_empty(current_path / "aa");
    try
    {
        cout << filesystem::is_empty(current_path / "test");
    }
    catch (...)
    {
        cout << "no a file named 'test'!\n";
    }




}
1