Monday, October 30, 2017

C++17: New file system library

C++17 added a file system library. Here is an example:

#include <filesystem>
#include <iostream>

// "experimental" and "v1" are needed for MSVS 2017.
namespace fs = std::experimental::filesystem::v1;

int main()
{
  fs::path myPath (".\\cpp17filesystem.cpp");
  fs::path myPath2(".\\junk.txt"           );
  bool     fileWasRemoved                   = false;

  std::cout << fs::exists(myPath)  << " "; // 1
  std::cout << myPath.stem()       << " "; // cpp17filesystem
  std::cout << myPath.extension()  << " "; // .cpp
  fs::remove(myPath2);
  std::cout << fs::exists(myPath2) << " "; // 0
  fs::copy(myPath, myPath2);
  std::cout << fs::exists(myPath2) << " "; // 1
  fileWasRemoved = fs::remove(myPath2);
  std::cout << fileWasRemoved      << " "; // 1
  fileWasRemoved = fs::remove(myPath2);
  std::cout << fileWasRemoved      << " "; // 0
  std::cout << std::endl;
  return 0;
}
// Output: 1 cpp17filesystem .cpp 0 1 1 0
References:
https://en.wikipedia.org/wiki/C%2B%2B17
http://en.cppreference.com/w/cpp/filesystem
http://www.bfilipek.com/2017/01/cpp17features.html#merged-file-system-ts
http://www.bfilipek.com/2017/08/cpp17-details-filesystem.html

No comments:

Post a Comment