VS2017 C++ filesystem

4 篇文章 0 订阅

VS2017 C++ 还没有正式支持filesystem,命名空间是std::experimental::filesystem。

https://zh.cppreference.com/w/cpp/filesystem/copy_file

注意:copy_file(from, to, option) ,以下情况报错(crash):1)源文件不存在报错,2)目标文件不允许覆盖(option没设置覆盖属性)。

一些常用的方法:

#include <iostream>
#include <filesystem>
#include <fstream>
#include <string>
using namespace std;
int main() {
  namespace fs = std::experimental::filesystem;
  cout << "current path: is " << fs::current_path() << endl;

  //to string
  string s = fs::current_path().generic_string();
  cout << s << endl;
  fs::path p1("c:\\tmp\\hello.txt");
  cout << "exists() = " << fs::exists(p1) << "\n"
       << "root_name() = " << p1.root_name() << "\n"
       << "root_path() = " << p1.root_path() << "\n"
       << "relative_path() = " << p1.relative_path() << "\n"
       << "parent_path() = " << p1.parent_path() << "\n"
       << "filename() = " << p1.filename() << "\n"
       << "stem() = " << p1.stem() << "\n"
       << "extension() = " << p1.extension() << "\n";

  auto p2 = p1.replace_extension(".bak");
  cout << "New filename: " << p2 << endl;

  auto p3 = p1.parent_path() / p1.stem();
  p3 += "_111.txt";
  cout << "New filename: " << p3 << endl;
  auto p = fs::current_path() / "1.txt";
  std::ofstream(p).put('a'); // 创建文件大小为 1
  std::cout << "File size = " << fs::file_size(p) << '\n';

  fs::remove(p);

  return 0;
}

/*输出
current path: is D:\git_clone\mycpp11\cpp11\test
D:/git_clone/mycpp11/cpp11/test
exists() = 0
root_name() = c:
root_path() = c:\
relative_path() = tmp\hello.txt
parent_path() = c:\tmp
filename() = hello.txt
stem() = hello
extension() = .txt
New filename: c:\tmp\hello.bak
New filename: c:\tmp\hello_111.txt
File size = 1
*/

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值