#include
#include
int main()
{
std::filesystem::path folderpath = "C:MyFolder";
if (std::filesystem::exists(folderpath))
{
std::cout << "The path: " << folderpath << " exists.";
}
else
{
std::cout << "The path: " << folderpath << " does not exist.";
}
}
Similarly, we can use the std::filesystem::path object to check if a file exists:
#include
#include
int main()
{
std::filesystem::path folderpath = "C:MyFoldermyfile.txt";
if (std::filesystem::exists(folderpath))
{
std::cout << "The file: " << folderpath << " exists.";
}
else
{
std::cout << "The file: " << folderpath << " does not exist.";
}
}
To iterate over folder elements, we use the std::filesystem::directory_iterator iterator:
#include
#include
int main()
{
auto myfolder = "C:MyFolder";
for (auto el : std::filesystem::directory_iterator(myfolder))
{
std::cout << el.path() << '
';
}
}
Here we iterate over the directory entries and print each of the elements full path using the .path() member function.
For Linux, we need to adjust the path and use the following instead:
#include
#include
int main()
{
auto myfolder = "MyFolder/";
for (auto el : std::filesystem::recursive_directory_iterator(myfolder))
{
std::cout << el.path() << '
';
}
}
To iterate over folder elements recursively, we use the std::filesystem::recursive_directory_iterator. This allows us to iterate recursively over all subfolders in a folder. On Windows, we would use:
#include
#include
int main()
{
auto myfolder = "C:MyFolder";
for (auto el : std::filesystem::recursive_directory_iterator(myfolder))
{
std::cout << el.path() << '
';
}
}
On Linux and similar OS-es, we would use the following path:
#include
#include
int main()
{
auto myfolder = "MyFolder/";
for (auto el : std::filesystem::directory_iterator(myfolder))
{
std::cout << el.path() << '
';
}
}
Below are some useful utility functions inside the std::filesystem namespace:
std::filesystem::create_directory for creating a directory
std::filesystem::copy for copying files and directories
std::filesystem::remove for removing a file or an empty folder
std::filesystem::remove_all for removing folders and subfolders
17.5 std::string_view
引用一段字符串并保留长度信息。
Copying data can be an expensive operation in terms of CPU usage. Passing substrings as function parameters would require making a copy of substrings. This is a costly operation. The string_view class template is an attempt to rectify that.
The string_view is a non-owning view of a string or a substring. It is a reference to something that is already there in the memory. It is implemented as a pointer to some character sequence plus the size of that sequence. With this kind of structure, we can parse strings efficiently.
The std::string_view is declared inside the header file. To create a string_view from an existing string, we write:
#include
#include
#include
int main()
{
std::string s = "Hello World.";
std::string_view sw(s);
std::cout << sw;
}