std::filesystem in C 17 provides cross-platform file and directory operation interfaces. ① Create a single-layer directory using create_directory(), and create_directories() using multi-layer directory; ② Remove() can be used to delete directories or files (only empty directories or files), and remove_all() can be used to delete recursively; ③ Use directory_iterator to traverse the directory, recursive_directory_iterator, and type can be judged by is_regular_file() or is_directory(); ④ Check the file status to exists(), is_regular_file(), is_directory() and file_size(), but file_size() will throw exceptions when the path does not exist; ⑤ Use the / operator for path stitching, and parsing paths can be used by parent_path(), filename(), and stem() and extension(); ⑥ Pay attention to the differences in exception handling and platform when using it. It is recommended to use the error_code parameter to avoid crashes.
Using C's std::filesystem
to handle file and directory operations is indeed much more convenient than before. It officially entered the standard library since C 17 and no longer needs to rely on platform-related APIs. If you have used Boost.Filesystem before, you will find that its interface is almost the same, just changed its name.

Below are some common uses and precautions, which are suitable for use directly in daily development.
Create and delete directories
Creating directories is a common requirement, such as a cache directory needs to be generated when the program is running.
std::filesystem::create_directory()
can create single-layer directories:

fs::create_directory("my_folder");
If you want to create a multi-layer directory (such as a/b/c
), you need to use create_directories()
, and this function will automatically help you create the middle path.
If you delete, use remove()
or remove_all()
, which can recursively delete the entire directory tree:

-
fs::remove("empty_dir")
: Only empty directories or files can be deleted. -
fs::remove_all("dir_with_files")
: Forced delete, including all contents inside.
Traversing the contents of the directory
You can use directory_iterator
to traverse the directory, which will list all files and subdirectories in the current directory:
for (const auto& entry : fs::directory_iterator("my_folder")) { std::cout << entry.path() << std::endl; }
If you want to recursively traverse subdirectories, you can use recursive_directory_iterator
, which will go down layer by layer. Note that the type can be determined by is_regular_file()
or is_directory()
.
Some small details:
- By default, the content pointed to by symbolic links will not be traversed.
- You can control whether to skip the point file (
.
and..
) through parameters.
Check whether the file exists, obtain size and other information
You can use these functions to quickly determine the state of a path:
-
fs::exists(path)
: Check if it exists -
fs::is_regular_file(path)
: Is it a normal file? -
fs::is_directory(path)
: Is it a directory -
fs::file_size(path)
: Get file size (unit bytes)
It should be noted that if the path does not exist, calling file_size()
will throw an exception. In order to avoid this, it is recommended to judge the existence first.
For example:
if (fs::exists("data.txt") && fs::is_regular_file("data.txt")) { std::cout << "File size: " << fs::file_size("data.txt") << " bytes\n"; }
Path stitching and analysis
Just use the /
operator to splice the path, which is very intuitive:
fs::path p = "C:/Users" / "name" / "Documents" / "notes.txt";
It also provides easy extraction of various parts of the path:
-
p.parent_path()
: parent directory -
p.filename()
: file name (including extension) -
p.stem()
: Part without extension -
p.extension()
: extension
For example, for notes.txt
:
-
stem()
isnotes
-
extension()
is.txt
Basically these common operations are. The design of std::filesystem
is more intuitive, but there are some pitfalls that need to be paid attention to. For example, some functions will throw exceptions by default when failing. It is best to add try-catch when using it, or pass an error_code parameter to avoid crashes.
In addition, although it is cross-platform, some behaviors may vary slightly under different systems, especially when it comes to permissions, symbolic links, and hidden files.
After using it well, you will find that it is much easier to write now than before, manually spelling strings and calling the system API.
The above is the detailed content of Using std::filesystem in C. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

SetupaMaven/GradleprojectwithJAX-RSdependencieslikeJersey;2.CreateaRESTresourceusingannotationssuchas@Pathand@GET;3.ConfiguretheapplicationviaApplicationsubclassorweb.xml;4.AddJacksonforJSONbindingbyincludingjersey-media-json-jackson;5.DeploytoaJakar

Maven is a standard tool for Java project management and construction. The answer lies in the fact that it uses pom.xml to standardize project structure, dependency management, construction lifecycle automation and plug-in extensions; 1. Use pom.xml to define groupId, artifactId, version and dependencies; 2. Master core commands such as mvnclean, compile, test, package, install and deploy; 3. Use dependencyManagement and exclusions to manage dependency versions and conflicts; 4. Organize large applications through multi-module project structure and are managed uniformly by the parent POM; 5.

First, use JavaScript to obtain the user system preferences and locally stored theme settings, and initialize the page theme; 1. The HTML structure contains a button to trigger topic switching; 2. CSS uses: root to define bright theme variables, .dark-mode class defines dark theme variables, and applies these variables through var(); 3. JavaScript detects prefers-color-scheme and reads localStorage to determine the initial theme; 4. Switch the dark-mode class on the html element when clicking the button, and saves the current state to localStorage; 5. All color changes are accompanied by 0.3 seconds transition animation to enhance the user

Use datetime.strptime() to convert date strings into datetime object. 1. Basic usage: parse "2023-10-05" as datetime object through "%Y-%m-%d"; 2. Supports multiple formats such as "%m/%d/%Y" to parse American dates, "%d/%m/%Y" to parse British dates, "%b%d,%Y%I:%M%p" to parse time with AM/PM; 3. Use dateutil.parser.parse() to automatically infer unknown formats; 4. Use .d

To generate hash values using Java, it can be implemented through the MessageDigest class. 1. Get an instance of the specified algorithm, such as MD5 or SHA-256; 2. Call the .update() method to pass in the data to be encrypted; 3. Call the .digest() method to obtain a hash byte array; 4. Convert the byte array into a hexadecimal string for reading; for inputs such as large files, read in chunks and call .update() multiple times; it is recommended to use SHA-256 instead of MD5 or SHA-1 to ensure security.

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

Yes, a common CSS drop-down menu can be implemented through pure HTML and CSS without JavaScript. 1. Use nested ul and li to build a menu structure; 2. Use the:hover pseudo-class to control the display and hiding of pull-down content; 3. Set position:relative for parent li, and the submenu is positioned using position:absolute; 4. The submenu defaults to display:none, which becomes display:block when hovered; 5. Multi-level pull-down can be achieved through nesting, combined with transition, and add fade-in animations, and adapted to mobile terminals with media queries. The entire solution is simple and does not require JavaScript support, which is suitable for large

Use the uuid module to obtain the MAC address of the first network card of the machine across the platform, without the need for a third-party library, and convert it into a standard format through uuid.getnode(); 2. Use subprocess to call system commands such as ipconfig or ifconfig, and combine it with regular extraction of all network card MAC addresses, which is suitable for scenarios where multiple network card information needs to be obtained; 3. Use the third-party library getmac, call get_mac_address() after installation to obtain the MAC, which supports query by interface or IP, but requires additional dependencies; in summary, if no external library is needed, the uuid method is recommended. If you need to flexibly obtain multi-network card information, you can use the subprocess solution to allow you to install the dependency getma.
