dirname
来源:https://stackoverflow.com/questions/3071665/getting-a-directory-name-from-a-filename
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
fs::path x{"/var/tmp/example.txt"};
std::cout << x.parent_path().string() << std::endl;
for(fs::path p : {"/var/tmp/example.txt", "/", "/var/tmp/."})
std::cout << "The parent path of " << p
<< " is " << p.parent_path() << '\n';
}
mkdir
来源:https://en.cppreference.com/w/cpp/filesystem/create_directory
bool create_directory( const std::filesystem::path& p );
(1) (since C++17)
bool create_directory( const std::filesystem::path& p, std::error_code& ec ) noexcept;
(2) (since C++17)
bool create_directory( const std::filesystem::path& p,
const std::filesystem::path& existing_p );
(3) (since C++17)
bool create_directory( const std::filesystem::path& p,
const std::filesystem::path& existing_p,
std::error_code& ec ) noexcept;
(4) (since C++17)
bool create_directories( const std::filesystem::path& p );
(5) (since C++17)
bool create_directories( const std::filesystem::path& p, std::error_code& ec );
(6) (since C++17)
- bool create_directory( const std::filesystem::path& p );
- bool create_directory( const std::filesystem::path& p, std::error_code& ec ) noexcept;
- bool create_directory( const std::filesystem::path& p, const std::filesystem::path& existing_p );
- bool create_directory( const std::filesystem::path& p, const std::filesystem::path& existing_p, std::error_code& ec ) noexcept;
- bool create_directories( const std::filesystem::path& p );
- bool create_directories( const std::filesystem::path& p, std::error_code& ec );
code
#include <cassert>
#include <cstdlib>
#include <filesystem>
int main()
{
std::filesystem::current_path(std::filesystem::temp_directory_path());
// Basic usage
std::filesystem::create_directories("sandbox/1/2/a");
std::filesystem::create_directory("sandbox/1/2/b");
// Directory already exists (false returned, no error)
assert(!std::filesystem::create_directory("sandbox/1/2/b"));
// Permissions copying usage
std::filesystem::permissions(
"sandbox/1/2/b",
std::filesystem::perms::others_all,
std::filesystem::perm_options::remove
);
std::filesystem::create_directory("sandbox/1/2/c", "sandbox/1/2/b");
std::system("ls -l sandbox/1/2");
std::system("tree sandbox");
std::filesystem::remove_all("sandbox");
}
读写文件
来源:https://stackoverflow.com/questions/38646062/c-high-performance-file-reading-and-writing-c14
写文件:
std::ofstream f("file.txt");
f.write(buffer.data(), buffer.size());
读文件:
std::string buffer;
std::ifstream f("file.txt");
f.seekg(0, std::ios::end);
buffer.resize(f.tellg());
f.seekg(0);
f.read(buffer.data(), buffer.size());