directory

  • 1. File system overview
    • 1. About paths
    • 2. How to recursively find all files in a path?
  • 2. Path classes and operations
    • Member functions of the path class
    • Non-member functions of the path class
  • Example 1: shows the use of the path object in C++17
  • Example 2: Shows the function in the Path class to decompose the Path component
  • Example 3: Shows some special operator usage related to path
  • Example 4: Show how to get disk space information

1. File system overview

The filesystem of the standard library provides a way to operate on a filesystem and its components, such as paths, regular files, and directories.

(1) File: a File system object that holds data and can be written or read. A file has a name and attributes, one of which is file type (2) Path: A series of elements identifying the location of the file, possibly including the file name

namespace fs = std::filesystem; Fs: : path p {” CheckPath. CPP “};

1. About paths

Absolute path: contains the full path and drive symbol relative path: does not contain the drive and the leading/symbol, the file exists relative to the current path.

// Create an alias for the namespace
namespace fs = std::filesystem;
fs::path p1("d:\\cpp\\hi.txt");		// Backslashes in strings are to be escaped
fs::path p2(a);		//Windows also supports forward slashes
fs::path p3(R"(d:\cpp\hi.txt)");	// Use raw string literals
Copy the code

2. How to recursively find all files in a path?

On Windows, you can use the tree /f command to list all subdirectories and files under the current directory.

If we wanted to use the C++17 file system library to write a similar program that recursively lists all subdirectories and files under the current directory, what would we do? Get all files/folders under the path, the folder path to traverse, and add the subfolder path to the list collection.

2. Path classes and operations

Member functions of the path class

Some important member functions instructions
+path(string) The constructor
+assign(string): path& Assign a value to the path object
+append(type p): path& Append p to the path. Type is string, path, or const char*. Equivalent to the /= operator; Add directory delimiters automatically
+concat(type p): path& Append p to the path. Type is string, path, or const char*. Equivalent to the += operator; Directory separators are not added automatically
+clear(): void Clear the path name of the storage
+remove_filename(): path& Removes the file name from the given path
+replace_filename(const path& replacement): path& Replace the file name with replacement
+root_name(): path Returns the root name of the common format path
+root_directory(): path Returns the root of the common format path
+root_path(): path Return the root path of the path, equivalent to root_name()/root_directory(), which is “the root name of the path/the root directory of the path”
+relative_path(): path Return the path relative to root-path
+parent_path(): path Returns the path to the parent directory
+filename(): path Returns the file name contained in the path
+stem(): path Returns the file name contained in the path, excluding the file extension
+extension(): path Returns the extension of the file name contained in the path
+empty(): bool Check whether the path is empty
+has_xxx(): bool Where “XXX” is the name of the function in the “decompose” category above. These functions check whether the path contains the corresponding path element

Non-member functions of the path class

Some important non-member functions instructions
operator/( const path& lhs, const path& rhs ) Join the two path components LHS and RHS with the preferred directory separator. Such as path p {} “C:”; P = p/” Users “/” batman “;
operator <<, >> (path p) Performs stream input or output on path P
s_regular_file( const path& p ): bool Check if the path is a regular file
is_directory( const path& p ): bool Check whether the path is a directory
is_empty( const path& p ): bool Checks whether the given path refers to an empty file or directory
current_path(): path
current_path( const path& p ): void Change the current path to p (similar to the Linux directive CD)
file_size( const path& p ): uintmax_t For regular file p, return its size; The result of trying to determine the size of a directory (and other unconventional files) is determined by the compiler
space(const path& p): space_info Returns information about the file system on which path name p is located. Space_info has three members: Capacity — the total size of the file system (in bytes), free — the free space of the file system (in bytes), and available — the free space available to normal processes (less than or equal to free).
status(const path& p): file_status Returns the type and properties of the file system object identified by p. The file_STATUS returned is a class that contains the file’s type (type) and permissions (Permissions)
remove(const path& p): bool Delete files or empty directories identified by path P
remove_all(const path& p): uintmax_t Recursively delete the contents of P (if it is a directory) and its subdirectories, and then delete P itself, returning the number of deleted files and directories
rename(const path& old_p,const path& new_p): void Move or rename file system objects identified by old_p to new_p(similar to the Linux directive mv)
copy( const path& from, const path& to ): void Copy files and directories. The other function bool copy_file(from, to) copies a single file
create_directory( const path& p ): bool Create directory p (the parent directory must already exist). If p already exists, the function does nothing
create_directories( const path& p ): bool Create directory p (the parent directory may not exist). If p already exists, the function does nothing

Example 1: shows the use of the path object in C++17

The contents of this section are as follows; Shows the c + +17The use of the path object inint main(a)
{
	// Define path, using raw string, escape string, forward slash string
	// Prints the default file delimiter
	// Check if it is a regular file, if so, output the file size
	// Check if it is a directory. If so, list its subdirectories
	// Check whether the path exists
}
Copy the code

Check out this article: how does VS change the C++ compilation standard

// C++17 support must be enabled
#include <iostream>
#include <filesystem>
#include <string>

namespace fs = std::filesystem;

int main(a)
{
	// Define path, using raw string, escape string, forward slash string
	// Generate a string
	fs::path p1{R"(C:\Users\15409\source\repos\file_test\Hello.txt)"};
	// Escape the string
	fs::path p2{ "C:\\Users\\15409\\source\\repos\\file_test\\Hello.txt" };
	// Forward slash string
	fs::path p3{ "C:/Users/15409/source/repos/file_test/Hello.txt" };

	// Prints the default file delimiter
	std::cout << fs::path::preferred_separator << std::endl;

	// Check if it is a regular file, if so, output the file size
	if (fs::is_regular_file(p2))
	{
		std::cout << p2 <<" s size is:"<<fs::file_size(p2) << std::endl;
	}
	// If it is not a regular file, it may be a directory
	else if (fs::is_directory(p2))
	{
		std::cout << p2 << "is a directory,includes:" << std::endl;
		// Prints out all its subdirectories
		for (auto& e : fs::directory_iterator(p2))
			std::cout << "" << e.path() << std::endl;
	}
	// Check whether the path exists
	else if (fs::exists(p2))
	{
		std::cout << p2 << "is a special file\n";
	}
	// File does not exist
	else
	{
		std::cout << p2 << "is not exist\n"<< std::endl; }}Copy the code

Effect:

1, If the file is not found in the path:



If this file exists in the path:





Output file size:



3, change p2 to file path:

fs::path p2{ "C:\\Users\\15409\\source\\repos\\file_test" };

Output the names of all files in this directory

Example 2: Shows the function in the Path class to decompose the Path component

The sample2: The contents to be shown in this section are as follows; Task: Show if there is a function in the Path class for decomposing Path components. Root name? Root path? Relative path? The parent path? The file name? File name trunk? The extension?Copy the code
/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * sample 2 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /
// C++17 support must be enabled
#include <iostream>
#include <filesystem>
#include <string>

namespace fs = std::filesystem;

using std::cout;
using std::endl;

int main(a)
{
	// Define path p
	fs::path p{R"(C:\Users\15409\source\repos\file_test\main.cpp)"};
	// Does the root name exist? Root path? Relative paths
	if (p.empty())
	{
		cout << "Path" << p << "is empty." << endl;
	}
	if(! fs::exists(p))
	{
		cout << "Path " << p << "dose not exist." << endl;
		std::exit(0);
	}
	cout << "root_name():" << p.root_name() < <"\n"
		<< "root_path():" << p.root_path() < <"\n"
		<< "relative_path():" << p.relative_path() < <"\n";
	cout << "parent_path():" << p.parent_path() < <"\n"
		<< "filename(): " << p.filename() < <"\n"
		<< "stem(): " << p.stem() < <"\n"
		<< "extension():" << p.extension() < <"\n";
	// Parent path? The file name? File name trunk? The extension?
}
Copy the code

Effect:

Example 3: Shows some special operator usage related to path

The sample3: The contents to be shown in this section are as follows; Task: Show some special operator usage related to pathCopy the code
// C++17 support must be enabled
#include <iostream>
#include <filesystem>
#include <string>

namespace fs = std::filesystem;

using std::cout;
using std::endl;

int main(a)
{
	// Define path p
	fs::path p1{ R"(C:\Users\15409\source\repos)" };
	fs::path p2{ R"(C:\Users\15409\source\repos)" };
	fs::path p3{ "" };
	/ / append and / =
	p1.append(R"(file_test)");
	p1 /= R"(p1)";
	cout << p1 << endl;
	//concat and +=, the difference between these two operations is that they do not actively add slashes
	p2.concat(R"(file_test)");
	p2 += R"(p2)";
	cout << p2 << endl;
	// Using the/operator to piece together a new path is a concatenation of a path object, not a string
	p3 = p3 / R"(file_test)" / R"(p3)";
	cout << p3 << endl;
}
Copy the code

Effect:

Example 4: Show how to get disk space information

The sample4: The contents to be shown in this section are as follows; Task: Show how to obtain disk space information Task: Use Filesystem ::space() function to get the space_info object for the partition where a path resides, and then display disk partition information.Copy the code
// C++17 support must be enabled
#include <iostream>
#include <filesystem>
#include <string>


int main(a)
{
	namespace fs = std::filesystem;

	using std::cout;
	using std::endl;

	// Define the path object
	fs::path p{"C:\\"};
	// Displays the total size and remaining size of the disk, in bytes
	cout << "C:total space: " << fs::space(p).capacity <<"b"<< endl;
	cout << "C:free space:" << fs::space(p).free << "b" << endl;

	cout << "C:total space: " << fs::space(p).capacity/(1024*1024*1024) < <"G" << endl;
	cout << "C:free space:" << fs::space(p).free/ (1024 * 1024 * 1024) < <"G" << endl;
}
Copy the code

Effect: My C drive…