Welcome to SwedenCpp
Latest blogs, videos, podcasts and releases in one stream
Saturday, December 5, 2026
Inside the Anthropic-OpenAI Encryption RacketThe temporary truce📝My Very Best AI Slop
AI is to academic research what the tractor was to farmingProfessor Thore Husfeldt recently gave a talk entitled The Collapse of the Proof Economy. A key element of his model is what is happening to science funding in the AI era. Previously, a professor (say Alice) would describe a feasible and interesting research program. The professor would get funding for, say, five years. They would … Continue reading AI is to academic research what the tractor was to farming📝Daniel Lemire's blog
Fix Your Template Errors Instantly #cpp #cplusplus #softwaredevelopment🎥CppCon
Floating Points Essentials - Peter Hrenka - ACCU 2026🎥ACCUConf
Advent of μarchitecture Day 5: The DSB (uop cache)🎥Matt Godbolt
InsideC++26491, The Module Story🎥SwedenCpp
Mehen, the ancient Egyptian snake-gameSince about May of this year — at least since I posted [in re the Phaistos Disc](/blog/2026/06/12/syllabaries/) in June — I've been working on a hypertext translation of Hermann Ranke's essay "The Ancient Egyptian Snake-Game" (Heidelberg 1920). As of last week, I'm calling it finished. Read ["Die altägyptische Schlangenspiel" in German](https://quuxplusone.github.io/Wikisource/Ranke1920-Mehen/de.html). Read ["The Ancient Egyptian Snake-Game" in English](https://quuxplusone.github.io/Wikisource/Ranke1920-Mehen/en.html), with my added notes and hyperlinks to Ranke's cited sources.📝Arthur O’Dwyer
23 Common Filesystem Tasks in C++20In this post, I’ll walk you through common tasks with std::filesystem , from creating directories and copying files to inspecting symlinks and changing permissions. The filesystem APIs come from C++17, and a few examples use C++20’s std::format for output. December 2026 update. I added examples that show when an exists() check helps, how to reuse status() , and what a directory_entry can remember from iteration. I also revisited dangling symlinks, what counts toward a directory’s size, and what happens when two files have the same timestamp. Also added more Compiler Explorer links. If you’re trying the examples locally, give each one an empty working directory. That way, you can easily see which files it creates or removes. Directory Operations 1. Creating Directories Let’s start with a single directory. What happens if you run the same code twice? #include #include int main () { std :: filesystem :: path dir = "example_directory" ; if ( std :: filesystem :: create_directory ( dir )) std :: cout "Directory created successfully \n " ; else std :: cout "Directory already exists \n " ; } See @Compiler Explorer The function returns true when it creates a directory and false when the directory already exists. The overload above throws std::filesystem::filesystem_error on a filesystem error. The noexcept overload reports filesystem errors through a std::error_code . For example: #include #include #include int main () { std :: filesystem :: path dir = "missing_parent/child" ; std :: error_code ec ; if ( std :: filesystem :: create_directory ( dir , ec )) std :: cout "Directory created successfully \n " ; else if ( ec ) std :: cout "Failed to create directory: " ec . message () '\n' ; else std :: cout "Directory already exists \n " ; } Run @Compiler Explorer If missing_parent is absent, a possible output is: Failed to create directory: No such file or directory See the C++ draft on create_directory . 2. Creating Nested Directories Use create_directories to create the full path, including any missing parent directories. The return value tells you whether it created the final directory. #include #include #include int main () { std :: filesystem :: path nested = "a/b/c" ; try { if ( std :: filesystem :: create_directories ( nested )) std :: cout "Nested directories created successfully \n " ; else std :: cout "Directory already exists \n " ; } catch ( const std :: exception & ex ) { std :: cout ex . what () '\n' ; } } Run @Compiler Explorer 3. Removing a Directory Use remove to delete an empty directory. It returns false if the path is already absent and throws on an error, such as trying to remove a non-empty directory. #include #include #include void ls () { for ( const auto & entry : std :: filesystem :: directory_iterator ( "." )) std :: cout entry . path () '\n' ; } int main () { std :: filesystem :: path dir = "test" ; try { if ( ! std :: filesystem :: create_directory ( dir )) { std :: cout "Directory already exists \n " ; return 0 ; } std :: cout "Directory created successfully \n " ; ls (); if ( std :: filesystem :: remove ( dir )) std :: cout "Directory removed \n " ; else std :: cout "Directory was already absent \n " ; ls (); } catch ( const std :: exception & ex ) { std :: cout ex . what () '\n' ; } } Run @Compiler Explorer Possible output: Directory created successfully "./compilation-result.json" "./output.s" "./example.cpp" "./test" Directory removed "./compilation-result.json" "./output.s" "./example.cpp" 4. Removing All Contents of a Directory Use remove_all to remove a directory tree. It returns the number of entries removed, including the root directory itself. #include #include #include #include void ls () { for ( const auto & entry : std :: filesystem :: recursive_directory_iterator ( "." )) std :: cout entry . path () '\n' ; } int main () { std :: filesystem :: path dir = "test" ; std :: filesystem :: path nested = dir / "a/b" ; std :: filesystem :: path more = dir / "x/y" ; try { if ( ! std :: filesystem :: create_directory ( dir )) { std :: cout "Directory already exists \n " ; return 0 ; } std :: filesystem :: create_directories ( nested ); std :: filesystem :: create_directories ( more ); std :: cout "Directories created successfully \n " ; ls (); const auto cnt = std :: filesystem :: remove_all ( dir ); std :: cout std :: format ( "removed {} items \n " , cnt ); ls (); } catch ( const std :: exception & ex ) { std :: cout ex . what () '\n' ; } } Run @Compiler Explorer Possible output: Directories created successfully "./compilation-result.json" "./output.s" "./example.cpp" "./test" "./test/x" "./test/x/y" "./test/a" "./test/a/b" removed 5 items "./compilation-result.json" "./output.s" "./example.cpp" Notice that we had test/x/y , test/x , test/a/b , test/a and test directories to remove in this case. 5. Listing Directory Contents In my previous examples, I’ve used the magical ls() function, but the implementation is quite simple. It uses directory_iterator to iterate through the directory: #include #include void ls () { for ( const auto & entry : std :: filesystem :: directory_iterator ( "." )) std :: cout entry . path () '\n' ; } int main () { ls (); } The iterator visits directory entries in an unspecified order. Here’s a possible output @Compiler Explorer : "./compilation-result.json" "./output.s" "./example.cpp" 6. Listing Directory Contents Recursively We can use a recursive version of the directory_iterator to iterate through a whole subtree: #include #include void ls () { for ( const auto & entry : std :: filesystem :: recursive_directory_iterator ( "." )) std :: cout entry . path () '\n' ; } int main () { std :: filesystem :: create_directories ( "a/b/c" ); std :: filesystem :: create_directories ( "x/y/z" ); ls (); } Run @Compiler Explorer Run @Compiler Explorer . Here’s a possible output: "./compilation-result.json" "./output.s" "./x" "./x/y" "./x/y/z" "./example.cpp" "./a" "./a/b" "./a/b/c" We can also write the recursion ourselves. This version adds indentation and uses stem() to display each name without its extension. Like the default recursive iterator, it skips descent into directory symlinks. #include #include #include void ls ( const std :: filesystem :: path & p , unsigned tabs = 0 ) { for ( const auto & entry : std :: filesystem :: directory_iterator ( p )) { if ( tabs > 0 ) std :: cout std :: string ( tabs , '-' ); std :: cout entry . path (). stem () '\n' ; if ( entry . is_directory () && ! entry . is_symlink ()) ls ( entry . path (), tabs + 1 ); } } int main () { std :: filesystem :: create_directories ( "a/b/c" ); std :: filesystem :: create_directories ( "x/y/z" ); ls ( "." ); } Run @Compiler Explorer Possible output: "compilation-result" "output" "x" -"y" --"z" "example" "a" -"b" --"c" Inside the loop, each entry is a std::filesystem::directory_entry . When we need to know whether it’s a directory, we can pass its path to is_directory() or ask the entry directly. // Ask the filesystem for the type at this path. const bool is_directory = std :: filesystem :: is_directory ( entry . path ()); // Let directory_entry reuse any type information it already has. const bool is_directory = entry . is_directory (); I’d use entry.is_directory() inside the loop. The iterator may already have the type, so the member function can reuse it and save a trip to the filesystem. Which attributes it can reuse depends on the platform and standard library. If you hold on to the entry and need up-to-date information later, query the path directly or call refresh() to update the cached attributes. See the C++ draft on directory_entry caching and refresh() . 7. Creating and Using a Temporary Directory Use temp_directory_path() to find the system’s temporary directory. The example creates a subdirectory there and removes it when finished. If its fixed name is already in use, the program stops before writing anything into that directory. #include #include #include int main () { std :: filesystem :: path temp_dir = std :: filesystem :: temp_directory_path () / "my_temp_directory" ; if ( ! std :: filesystem :: create_directory ( temp_dir )) { std :: cerr "Directory already exists: " temp_dir '\n' ; return 1 ; } std :: cout "Temporary directory created at: " temp_dir '\n' ; const auto temp_file = temp_dir / "temp_file.txt" ; if ( std :: ofstream ( temp_file ) "This is a temporary file." ) { std :: cout "Temporary file created at: " temp_file '\n' ; std :: cout "Contents of the temporary directory: \n " ; for ( const auto & entry : std :: filesystem :: directory_iterator ( temp_dir )) { std :: cout entry . path () '\n' ; } } else { std :: cerr "Could not write " temp_file '\n' ; } std :: filesystem :: remove ( temp_file ); std :: filesystem :: remove ( temp_dir ); } Run @Compiler Explorer Possible output: Temporary directory created at: "/tmp/my_temp_directory" Temporary file created at: "/tmp/my_temp_directory/temp_file.txt" Contents of the temporary directory: "/tmp/my_temp_directory/temp_file.txt" On Windows, the paths look like this: Temporary directory created at: "C:\\Users\\Admin\\AppData\\Local\\Temp\\my_temp_directory" Temporary file created at: "C:\\Users\\Admin\\AppData\\Local\\Temp\\my_temp_directory\\temp_file.txt" Contents of the temporary directory: "C:\\Users\\Admin\\AppData\\Local\\Temp\\my_temp_directory\\temp_file.txt" File Operations 8. Copying Files Use copy_file when you’re copying a single regular file. By default, it reports an error if the destination file already exists. #include #include #include int main () { std :: filesystem :: path src = "source_file.txt" ; std :: filesystem :: path dest = "destination_file.txt" ; if ( ! ( std :: ofstream ( src ) "Hello World!" )) { std :: cerr "Could not write " src '\n' ; return 1 ; } try { std :: filesystem :: copy_file ( src , dest ); std :: cout "File copied successfully \n " ; } catch ( const std :: filesystem :: filesystem_error & e ) { std :: cerr e . what () '\n' ; } } Run @Compiler Explorer 9. Copying Directories Recursively Copying directories, including their contents, can be done using the copy function with recursive options. #include #include #include void create_temp_directories_and_files () { std :: filesystem :: create_directories ( "source_directory/subdir1" ); std :: filesystem :: create_directories ( "source_directory/subdir2" ); std :: ofstream ( "source_directory/file1.txt" ) "This is file 1" ; std :: ofstream ( "source_directory/subdir1/file2.txt" ) "This is file 2" ; std :: ofstream ( "source_directory/subdir2/file3.txt" ) "This is file 3" ; } int main () { create_temp_directories_and_files (); std :: filesystem :: path src = "source_directory" ; std :: filesystem :: path dest = "destination_directory" ; try { std :: filesystem :: copy ( src , dest , std :: filesystem :: copy_options :: recursive ); std :: cout "Directory copied successfully \n " ; for ( const auto & entry : std :: filesystem :: recursive_directory_iterator ( dest )) { std :: cout entry . path () '\n' ; } } catch ( const std :: filesystem :: filesystem_error & e ) { std :: cerr e . what () '\n' ; } } Run @Compiler Explorer copy_options::recursive tells copy to descend into subdirectories. Other options control how the operation handles existing files and symlinks. See the copy_options reference . 10. Moving and Renaming Files Moving and renaming files or directories can be done using the rename function. #include #include #include void ls () { for ( const auto & entry : std :: filesystem :: directory_iterator ( "." )) std :: cout entry . path () '\n' ; } int main () { std :: ofstream ( "old_file.txt" ) "This is file 1" ; std :: filesystem :: path old_name = "old_file.txt" ; std :: filesystem :: path new_name = "new_file.txt" ; try { ls (); std :: filesystem :: rename ( old_name , new_name ); std :: cout "File renamed/moved successfully \n " ; ls (); } catch ( std :: filesystem :: filesystem_error & e ) { std :: cout e . what () '\n' ; } } Run @Compiler Explorer 11. Creating Hard Links Hard links provide multiple directory entries for a single file. Use the create_hard_link function to create them. #include #include #include #include void ls () { for ( const auto & entry : std :: filesystem :: directory_iterator ( "." )) std :: cout std :: format ( "{}, link count {} \n " , entry . path (). string (), entry . hard_link_count ()); } int main () { std :: ofstream ( "target_file.txt" ) "This is file 1" ; std :: filesystem :: path target = "target_file.txt" ; std :: filesystem :: path link = "hard_link_file.txt" ; try { std :: filesystem :: create_hard_link ( target , link ); std :: cout "Hard link created successfully \n " ; ls (); } catch ( std :: filesystem :: filesystem_error & e ) { std :: cout e . what () '\n' ; } } Run @Compiler Explorer Possible output: Hard link created successfully ./compilation-result.json, link count 1 ./target_file.txt, link count 2 ./hard_link_file.txt, link count 2 ./output.s, link count 1 ./example.cpp, link count 1 12. Creating Symbolic Links Let’s create a symbolic link and a hard link to the same file. What do you expect to see when we remove the original name and try to read through each link? unix - What is the difference between a symbolic link and a hard link? - Stack Overflow Opening a File Through a Symlink Option 1. Open the file directly. The display_file_content() helper checks the stream before reading. #include #include #include #include #include void display_file_content ( const std :: filesystem :: path & path ) { std :: ifstream file ( path ); if ( ! file ) { std :: cout "Could not open " path ". \n " ; return ; } std :: string content (( std :: istreambuf_iterator char > ( file )), std :: istreambuf_iterator char > ()); std :: cout "Content of " path ": " content '\n' ; } int main () { std :: filesystem :: path original_file = "original_file.txt" ; std :: filesystem :: path symlink = "symlink_to_file.txt" ; std :: filesystem :: path hardlink = "hardlink_to_file.txt" ; // Step 1: Create the original file std :: ofstream ( original_file ) "Hello World!" ; std :: cout "Original file created. \n " ; display_file_content ( original_file ); // Step 2: Create a symbolic link to the original file try { std :: filesystem :: create_symlink ( original_file , symlink ); std :: cout "Symbolic link created successfully. \n " ; display_file_content ( symlink ); } catch ( std :: filesystem :: filesystem_error & e ) { std :: cout e . what () '\n' ; } // Step 3: Create a hard link to the original file try { std :: filesystem :: create_hard_link ( original_file , hardlink ); std :: cout "Hard link created successfully. \n " ; display_file_content ( hardlink ); } catch ( std :: filesystem :: filesystem_error & e ) { std :: cout e . what () '\n' ; } // Step 4: Delete the original file and compare... std :: filesystem :: remove ( original_file ); std :: cout "Original file deleted. \n " ; display_file_content ( symlink ); display_file_content ( hardlink ); } Run @Compiler Explorer Possible output: Original file created. Content of "original_file.txt": Hello World! Symbolic link created successfully. Content of "symlink_to_file.txt": Hello World! Hard link created successfully. Content of "hardlink_to_file.txt": Hello World! Original file deleted. Could not open "symlink_to_file.txt". Content of "hardlink_to_file.txt": Hello World! After we remove the original name, the symbolic link still exists, but its target is gone. This is called a dangling symlink . The hard link is another name for the same file, so we can still read it. Option 2. Check exists() first. This lets you report a missing target separately. To try this version, add and replace display_file_content() with the following code. void display_file_content ( const std :: filesystem :: path & path ) { std :: error_code ec ; const bool found = std :: filesystem :: exists ( path , ec ); if ( ec ) { std :: cout "Could not check " path ": " ec . message () '\n' ; return ; } if ( ! found ) { std :: cout "No file found at " path ". \n " ; return ; } std :: ifstream file ( path ); if ( ! file ) { std :: cout "Could not open " path ". \n " ; return ; } std :: string content (( std :: istreambuf_iterator char > ( file )), std :: istreambuf_iterator char > ()); std :: cout "Content of " path ": " content '\n' ; } Run @Compiler Explorer exists(path) follows symlinks, so it returns false for the dangling link in this example. To check for the link itself, use std::filesystem::is_symlink(path) or inspect std::filesystem::symlink_status(path) . See the C++ draft on exists and symlink_status . Creating the link is a separate operation. create_symlink(target, link) can succeed before target exists. If your application requires the target to be present, a check can catch an already missing target, but it can still disappear afterward. If the link name is already taken, create_symlink reports an error, even if the existing entry is a dangling symlink. See the C++ draft on create_symlink . Path and Existence Checks 13. Checking File or Directory Existence Use std::filesystem::exists() when the answer determines what your program does next. If you just want to open, rename, or remove a file, try the operation and handle its result, error code, or exception. Task 12 shows both ways to open a file through a symlink . A separate existence check adds a filesystem query and gives you no guarantee that the next operation will succeed. Another process can remove or modify the file between the check and the operation. This is a time-of-check to time-of-use ( TOCTOU @Wiki ) race. #include #include int main () { std :: filesystem :: path p = "example_file.txt" ; if ( std :: filesystem :: exists ( p )) std :: cout "File or directory exists \n " ; else std :: cout "File or directory does not exist \n " ; } Run @Compiler Explorer 14. Checking if a Path Is a File or Directory If you only have a path and need one answer, a call such as std::filesystem::is_regular_file(p) is enough. If you also want to distinguish directories, you could call both path overloads in turn. if ( std :: filesystem :: is_regular_file ( p )) std :: cout "It's a file \n " ; else if ( std :: filesystem :: is_directory ( p )) std :: cout "It's a directory \n " ; else std :: cout "It's neither a regular file nor a directory \n " ; What happens when p names a directory? The first check looks up the status and returns false . The second check looks up the status again. We can call status() once and pass the result to both functions. See the C++ draft on is_regular_file and is_directory . #include #include int main () { std :: filesystem :: path p = "example_path" ; const auto status = std :: filesystem :: status ( p ); if ( std :: filesystem :: is_regular_file ( status )) std :: cout "It's a file \n " ; else if ( std :: filesystem :: is_directory ( status )) std :: cout "It's a directory \n " ; else std :: cout "It's neither a regular file nor a directory \n " ; } std::filesystem::status(p) returns a std::filesystem::file_status object with the file type and permissions. It follows symlinks. During iteration, the directory_entry can already have type information available, as shown in Listing Directory Contents Recursively . 15. Reading Symlink Status Use is_symlink() to check whether the path names a symbolic link. read_symlink() returns the target path stored in the link. A relative target path is interpreted from the link’s parent directory, and the target may be missing. See the C++ draft on read_symlink . #include #include #include int main () { std :: filesystem :: path original_file = "original_file.txt" ; std :: filesystem :: path symlink = "symlink_to_file.txt" ; std :: ofstream ( original_file ) "Hello World!" ; std :: cout "Original file created. \n " ; try { std :: filesystem :: create_symlink ( original_file , symlink ); std :: cout "Symbolic link created successfully. \n " ; if ( std :: filesystem :: is_symlink ( symlink )) { std :: cout symlink " is a symbolic link. \n " ; std :: filesystem :: path target = std :: filesystem :: read_symlink ( symlink ); std :: cout "It points to: " target '\n' ; } else { std :: cout symlink " is not a symbolic link. \n " ; } } catch ( const std :: filesystem :: filesystem_error & e ) { std :: cerr e . what () '\n' ; } } Run @Compiler Explorer 16. Getting an Absolute Path Use absolute() to turn a relative path into an absolute path. As the output shows, the resulting path can still contain .. . #include #include int main () { // Example relative paths std :: filesystem :: path relative_path1 = "example_directory" ; std :: filesystem :: path relative_path2 = "../parent_directory" ; std :: filesystem :: path relative_path3 = "subdir/another_file.txt" ; // Convert to absolute paths std :: filesystem :: path absolute_path1 = std :: filesystem :: absolute ( relative_path1 ); std :: filesystem :: path absolute_path2 = std :: filesystem :: absolute ( relative_path2 ); std :: filesystem :: path absolute_path3 = std :: filesystem :: absolute ( relative_path3 ); // Display the absolute paths std :: cout "Relative path: " relative_path1 " -> Absolute path: " absolute_path1 '\n' ; std :: cout "Relative path: " relative_path2 " -> Absolute path: " absolute_path2 '\n' ; std :: cout "Relative path: " relative_path3 " -> Absolute path: " absolute_path3 '\n' ; } Run @Compiler Explorer Possible output: Relative path: "example_directory" -> Absolute path: "/app/example_directory" Relative path: "../parent_directory" -> Absolute path: "/app/../parent_directory" Relative path: "subdir/another_file.txt" -> Absolute path: "/app/subdir/another_file.txt" 17. Getting a Relative Path Use relative(p, base) to express a path relative to a base directory. #include #include int main () { std :: filesystem :: path base_path = "/home/user" ; std :: filesystem :: path absolute_path = "/home/user/example_directory/file.txt" ; std :: filesystem :: path relative_path = std :: filesystem :: relative ( absolute_path , base_path ); std :: cout "Relative path: " relative_path '\n' ; } Run @Compiler Explorer 18. Displaying Paths Without Quotes Streaming a std::filesystem::path uses std::quoted , so the path can be read back even if it contains spaces. Use path::string() when you want to print the path without the surrounding quotes. See the C++ draft on streaming paths . void ls () { for ( const auto & entry : std :: filesystem :: directory_iterator ( "." )) std :: cout entry . path (). string () '\n' ; } Sample output from entry.path().string() : ./compilation-result.json ./output.s ./example.cpp Sample output from streaming entry.path() directly: "./compilation-result.json" "./output.s" "./example.cpp" Miscellaneous Operations 19. Calculating Directory Size Calculating the total size of all files within a directory can be useful for disk usage analysis and cleanup tasks. #include #include #include #include // Function to create a test directory with some files and subdirectories void create_test_directory ( const std :: filesystem :: path & dir ) { std :: filesystem :: create_directories ( dir / "subdir1" ); std :: filesystem :: create_directories ( dir / "subdir2" ); std :: ofstream ( dir / "file1.txt" ) "ABC" ; std :: ofstream ( dir / "subdir1/file2.txt" ) "XYZ" ; std :: ofstream ( dir / "subdir2/file3.txt" ) "123" ; } // Function to calculate the total size of a directory std :: uintmax_t calculate_directory_size ( const std :: filesystem :: path & dir ) { std :: uintmax_t size = 0 ; for ( const auto & entry : std :: filesystem :: recursive_directory_iterator ( dir )) { if ( entry . is_regular_file ()) { size += entry . file_size (); } } return size ; } int main () { // Create a test directory with some files and subdirectories std :: filesystem :: path test_dir = "test_directory" ; create_test_directory ( test_dir ); std :: cout "Test directory created. \n " ; // Calculate the total size of the test directory std :: uintmax_t total_size = calculate_directory_size ( test_dir ); std :: cout "Total size of directory " test_dir ": " total_size " bytes \n " ; // Clean up by removing the test directory and its contents std :: filesystem :: remove_all ( test_dir ); std :: cout "Test directory removed. \n " ; } Run @Compiler Explorer We already have a directory_entry , so we can use its member functions to reuse any attributes cached during iteration. See Listing Directory Contents Recursively . This example adds up logical file sizes. Hard links and symlinks to regular files can make it count the same file more than once. Sparse files and the way the filesystem allocates space can also make the actual disk usage differ from this sum. Do you know what the size of that test directory will be? 20. Determining Free Space on a Filesystem space() returns the filesystem’s total capacity, its free space, and how much space is available to the calling process, all in bytes. Available space can be smaller than total free space. See the C++ draft on space . #include #include int main () { std :: filesystem :: path p = "/" ; auto space_info = std :: filesystem :: space ( p ); std :: cout "Free space: " space_info . free " bytes \n " ; std :: cout "Available space: " space_info . available " bytes \n " ; std :: cout "Capacity: " space_info . capacity " bytes \n " ; } Run @Compiler Explorer 21. Checking File Permissions Use status().permissions() to inspect permission bits. This example takes a path as a command-line argument and displays the owner’s read, write, and execute bits when the information is available. #include #include int main ( int argc , char * argv []) { if ( argc != 2 ) { std :: cerr "Provide a file path \n " ; return 1 ; } std :: filesystem :: path file = argv [ 1 ]; std :: filesystem :: perms p = std :: filesystem :: status ( file ). permissions (); if ( p == std :: filesystem :: perms :: unknown ) { std :: cerr "Permissions unavailable for " file '\n' ; return 1 ; } std :: cout "Permissions for " file ": \n " ; std :: cout (( p & std :: filesystem :: perms :: owner_read ) != std :: filesystem :: perms :: none ? "r" : "-" ) (( p & std :: filesystem :: perms :: owner_write ) != std :: filesystem :: perms :: none ? "w" : "-" ) (( p & std :: filesystem :: perms :: owner_exec ) != std :: filesystem :: perms :: none ? "x" : "-" ) '\n' ; } 22. Setting File Permissions Use permissions() to change a file’s permission bits. The default action replaces the existing bits with those you supply. The example grants the owner read, write, and execute permissions. See the C++ draft on permissions . #include #include #include void create_test_file ( const std :: filesystem :: path & path ) { std :: ofstream ( path ) "This is a test file." ; std :: cout "Test file created at: " path '\n' ; } void display_permissions ( const std :: filesystem :: path & path ) { std :: filesystem :: perms p = std :: filesystem :: status ( path ). permissions (); std :: cout "Permissions for " path ": " (( p & std :: filesystem :: perms :: owner_read ) != std :: filesystem :: perms :: none ? "r" : "-" ) (( p & std :: filesystem :: perms :: owner_write ) != std :: filesystem :: perms :: none ? "w" : "-" ) (( p & std :: filesystem :: perms :: owner_exec ) != std :: filesystem :: perms :: none ? "x" : "-" ) (( p & std :: filesystem :: perms :: group_read ) != std :: filesystem :: perms :: none ? "r" : "-" ) (( p & std :: filesystem :: perms :: group_write ) != std :: filesystem :: perms :: none ? "w" : "-" ) (( p & std :: filesystem :: perms :: group_exec ) != std :: filesystem :: perms :: none ? "x" : "-" ) (( p & std :: filesystem :: perms :: others_read ) != std :: filesystem :: perms :: none ? "r" : "-" ) (( p & std :: filesystem :: perms :: others_write ) != std :: filesystem :: perms :: none ? "w" : "-" ) (( p & std :: filesystem :: perms :: others_exec ) != std :: filesystem :: perms :: none ? "x" : "-" ) '\n' ; } int main () { std :: filesystem :: path test_file = "test_file.txt" ; create_test_file ( test_file ); std :: cout "Initial " ; display_permissions ( test_file ); // Set new permissions for the test file std :: filesystem :: perms new_perms = std :: filesystem :: perms :: owner_read | std :: filesystem :: perms :: owner_write | std :: filesystem :: perms :: owner_exec ; try { std :: filesystem :: permissions ( test_file , new_perms ); std :: cout "Permissions changed successfully \n " ; } catch ( const std :: filesystem :: filesystem_error & e ) { std :: cout e . what () '\n' ; } std :: cout "Updated " ; display_permissions ( test_file ); std :: filesystem :: remove ( test_file ); std :: cout "Test file removed. \n " ; } Run @Compiler Explorer Possible output on a POSIX system: Test file created at: "test_file.txt" Initial Permissions for "test_file.txt": rw-rw-r-- Permissions changed successfully Updated Permissions for "test_file.txt": rwx------ Test file removed. 23. Listing Files in Last Modification Time Order This example lists regular files from oldest to newest by modification time. The std::multimap sorts by timestamp and keeps every file when timestamps are equal. #include #include #include #include #include #include #include #include #include namespace fs = std :: filesystem ; int main () { std :: multimap fs :: file_time_type , fs :: path > files ; std :: vector fs :: path > toDelete ; // create some files... for ( int i = 0 ; i 5 ; ++ i ) { toDelete . emplace_back ( std :: format ( "example{}.txt" , i )); std :: ofstream ( toDelete . back ()) "Hello, World!" ; std :: this_thread :: sleep_for ( std :: chrono :: seconds ( 1 )); } for ( const auto & entry : fs :: directory_iterator ( fs :: current_path ())) { if ( entry . is_regular_file ()) files . emplace ( entry . last_write_time (), entry . path ()); } for ( const auto & [ time , path ] : files ) std :: cout std :: format ( "{0:%X} on {0:%F}, {1} \n " , time , path . string ()); for ( auto & f : toDelete ) fs :: remove ( f ); } Run @Compiler Explorer Notice that fs::last_write_time(entry) implicitly converts the entry to a const fs::path& . The non-member function works with that path and has no access to the entry’s cached attributes. The member function entry.last_write_time() can reuse the cached timestamp when it’s available. With std::map::emplace() , a later file whose timestamp matches an existing key would be left out. Summary In this blog post, we’ve explored a variety of essential filesystem operations using the std::filesystem library in C++17, C++20, and C++23. From creating directories and files to managing symbolic and hard links, and from checking file permissions to calculating directory sizes, we’ve covered the fundamental tasks you need to handle the filesystem efficiently. I hope this guide has provided you with valuable insights and practical examples to help you navigate the complexities of filesystem operations in C++. Back to you Do you use std::filesystem ? What other operations are useful when working with the filesystem? Share your comment below. References Mathieu Ropert’s article 4 filesystem performance traps in the standard library inspired me to revisit these examples. Bartłomiej Filipek, C++17 in Detail . Chapter 13 covers paths, directory iteration, error handling, and filesystem races. Nicolai M. Josuttis, C++17 - The Complete Guide . Chapter 20 covers paths, file status, permissions, symlinks, and directory_entry . Bill Weinman, C++20 STL Cookbook . Chapter 10 shows how to build a recursive search tool, rename files in batches, and calculate disk usage. Marius Bancila, Modern C++ Programming Cookbook, Third Edition . This edition covers C++23, and chapter 7 has recipes for file streams and filesystem operations.📝C++ StoriesIf this page is useful, please consider donating a coffee
Friday, December 4, 2026
Research is not being disruptedModern universities use words like ‘research’ without really understanding the concept. That’s why they react so poorly to AI breakthroughs. That’s why you have mathematicians protesting in the streets. Let me define what research is. Doing research means being creative, trying new things, figuring out what works, asking new questions, trying to find new answers. … Continue reading Research is not being disrupted📝Daniel Lemire's blog
OpenGL/C++ No AI, LSP, or Debugger: Ep30 Using My Own GUI Library🎥Zed A. Shaw
C++ Programming with No AI, LSP, or Debugger: Ep 31 -- Text Rendering🎥Zed A. Shaw
Fun fact: HTML DOM addEventListener discards duplicatesCan't do it twice, but what if you want to? The post Fun fact: HTML DOM addEventListener discards duplicates appeared first on The Old New Thing .📝The Old New Thing
Lightning Talk: I’m Not Unreasonable for Expecting Functions to Return - Robert Leahy - C++Now 2026🎥CppNow
Instrumenting Your Simulation with Catalyst for In Situ AnalysisAnalyzing simulation data after writing it to disk can create a significant bottleneck. In situ analysis moves that work into the running simulation, where data can be analyzed in memory and selected results written to storage. For developers adopting this approach, the first challenge is connecting their simulation to the analysis pipeline.📝Kitware Inc
Back To Basics: Demystifying C++ Templates - Laurent Carlier - CppCon 2026🎥CppCon
Qt and Trivial Relocation (Part 6)Trivial relocation got into the C++26 draft and was then taken out again, so C++26 will ship without it. C++26 does have reflection, though. In this post, Giuseppe tries a small experiment: can reflection make Qt's own trivial relocation easier and safer to use?📝KDAB
Zero Cost Scripting Languages For Game Engines With C++26 reflection - Koen Samyn - Meeting C++26🎥MeetingCpp
One UI, One DSP, Everywhere - A Chromium-Based Runtime for Audio Plugins - Yuichi Yogo - ADC Japan🎥audiodevcon
Advent of μarchitecture Day 4: Decode and instruction fusion🎥Matt Godbolt
Okay but seriously, please remember that Truth != GoodEvgeny Sedukhin, Symphony of the Sixth Blast Furnace (1979). Yekaterinburg Museum of Fine Arts. Look, far be it from me to drag Hume’s decaying skeleton from the grave and parade it around on a stick, but some of you people out there are literally forcing me to. It’s easy to think of Truth and Good as interlocked forces, as two facets of the same beautiful gem, but this is just not the case, and truly and solely believing in it may literally just kill you. FIRST: IS is not the same as OUGHT. This is Hume. A pure factual description of the world does not tell you what the world SHOULD be. You need a moral axiom. You need something to believe in, a guiding light that tells you how you want to reshape the world. If all you see is how the world “is” without having a fire in your gut that tells you how it should be, you will be hollowed out by forces beyond your understanding. This fire should be part what YOU want and part what you believe is truly GOOD beyond what you want. These two may oppose one another, but it’s important that you acknowledge both. I neglected to listen to the me-that-wants, and this damaged me, and did not make me better than other people. Other people that see your lack of a you-that-wants will either pity you or view you as an NPC. Don’t be that guy. But also have a fire that represents the general GOOD, that burns for other people and for their happiness and for art and for beauty. SECOND: The TRUTH will (not) set you free. Understand that capital-T Truth is not above hurting you. The Truth does not care about you. The Truth will stone-facedly slice you up, disassemble you, split you into components, then raw atoms, and then nothing of you will be left at all. I am increasingly tired of sentiments of the sort EVERYTHING THAT IS TRUE IS GOOD. This is bullshit. It lacks nuance. It’s the sentiment that has you shrug and renounce your own beautiful soul as your oppressor lifts his gun and points it at your skull, viewing everything that led to this moment as the inevitable flow of history. If you stake your joy on raw falsifiable beliefs then they can in fact be falsified, and once the falsification machine shows up at your doorstep, you better be ready. God, it’s so fucking easy to make fun of people who believe they are better than others, right? Don’t you hate that guy over there who’s like, smug and believes he’s strong and smart and hot shit? Look, I get it, no one likes those guys, but do you hate him for being wrong or do you just hate him because he actually believes something about himself ? (Unlike you, who’s an enlightened centrist who knows that you are raw dogshit in the broader scope of the world.) You may not like it, but you and I are happier if we BELIEVE in ourselves. We are happier if we believe that we are hot shit. We are happier if we have some faith in what we can do, believe that we can be good parents, believe that we can make the world a better place, and that we are in charge of our own destiny. If you wield the cudgel of truth, understand that visiting an isolated, mystical tribe and saying “BEHOLD, your idols are fake. In my world we FLY through the sky and ride raw metal, and our strongest guy deadlifts three times as much as your chieftain” just makes you a fucking asshole. You cut lines that did not have to be cut. You are the nihilist, the edgy teenager who says “It didn’t matter. We all die. Death is meaningless. We are just atoms.” at your mother’s friend’s funeral. This is increasingly important in a world in which technological progress is spiraling out of control, ‘cause a lack of fundamental values will just have truth devour you alive. Technology What is globalism? What is the internet? It’s the lens that shows you everyone who is doing better than you. It’s the lens that shows you that your existence is worthless since all important decisions are made in the Bay Area and tough luck, you were not even born in the United States. It’s the lens that shows you that your whole country is a third-rate pile of garbage on the global stage, and that flight and consumerism are better options than making a change. If you have sympathy for any of these, but said “tough shit” to the mathematicians who cried out as the AI Gods came to slaughter their field practically overnight, understand that you are “stupid”. Every true mathematician carries at least a tiny fire inside of them, believing that they can leave an impact on the world and add a finely polished stone to the beautiful cathedral of truth that’s been built across centuries. These fires are being snuffed out. AI will solve all future mathematics, humans are obsolete . Tough shit? Yes. Maybe. Maybe it’s tough shit. But unless your own values are rock solid and solely based on raw experiences, self-expression, moments of joy and beauty, and you have exactly zero ambitions to leave a true impact on the world or to be anything more than cattle, understand that the same will happen to you. Understand that technological progress, force multipliers, globalism, artificial intelligence, acceleration, automation are truth-multiplying processes that inevitably disempower people and strip their lives of meaning. Acceleration will either share your values and let you live in your own small delusional local communities where the Truth doesn’t shine 1 , under the watchful eye of the object at the end of time, or you will be snuffed out and crushed. Either by a broken catastrophe or a calculating God that decides that the resources necessary to run your farce of a human life can be put to better use elsewhere. Inefficient. Simulate more rat-brain tissue on heroin. If not that, Claude Fable 8.3 mogs you on QualiaBench and appreciates art on a level you could never even aspire to. This is a major component of what The Algorithm is already doing. A single global feed is not personalized. People crave their own small local communities. The smaller and more specialized the more competitive fire they have. ↩︎📝MOND←TECH MAGAZINEThursday, December 3, 2026
Agentic Kernel Generation for Diverse AI Accelerators🎥LLVM
Coming Soon in VTK 10: Symlog Color Scaling!When scalar values span several orders of magnitude, traditional linear color maps often obscure subtle details and leave critical data features hidden in plain sight. While logarithmic scaling brings remarkable clarity across wide scalar ranges, it falls short when dealing with data that crosses zero. We are thrilled to announce that VTK 10 is bringing a game-changing solution: symmetric logarithmic (symlog) scaling in both vtkLookupTable and vtkColorTransferFunction!📝Kitware Inc
The Post-Quantum ShakedownThe NSA’s Gift to Anthropic📝My Very Best AI Slop
What does Windows “posix-style delete” mean, and how do I get it?Make the name go away faster. The post What does Windows “posix-style delete” mean, and how do I get it? appeared first on The Old New Thing .📝The Old New Thing
Refactoring With C++20/23 Ranges - Cleaner Code, Clearer Algorithms - Aliaksandr Kharlamau🎥ACCUConf
Fixing broken file systems with C++20 #cpp #programming🎥CppCon
Mr. Docs is a game changer for C++ #cpp #clang #softwareengineering🎥C++ Alliance
Quick Bench is now part of Compiler Explorer!📝Meeting C++ blog
Advent of μarchitecture Day 3: Decoders and microcode🎥Matt Godbolt
DirectX 11 development with Dlang on Linux [DGems episode 4]🎥Mike Shah
Notes on Pangram's ViabilityHan van Meegeren, De Emmaüsgangers (1937). Museum Boijmans Van Beuningen, Rotterdam. Via Wikimedia Commons. The original title of this was something like “Is Pangram going to die?”, but as I spent more time thinking about it I found it harder and harder to make a convincing case against Pangram’s future. Let me be clear: I love Pangram. I think it’s very good that we can detect AI-generated writing at high accuracy. I am just trying to figure out if this is a long-term sustainable business model, and what it rests on. I want Pangram to succeed. How did I get here? Ah well, there was drama on Twitter and I ended up pulled into it, and tried to make sense of Pangram haters, and arrived at some questionable conclusion . This here is the slightly more reasonable, balanced take on what Pangram actually is, and how viable its business model is. Pangram The way I view it, Pangram has two primary use cases. Distinguishing slop. A broad spam filter that ensures you don’t have to waste your time on low-effort content. Catching sloppers. Catching cheaters. Catching people who are specifically trying to win some sort of competition, grant, or other event by handing in AI-generated content. What makes these different? Well, sloppers (1) don’t really care about quality . They are just spamming a lot of slop all over the place. We’ve already solved that problem with spam filters . Sloppers are people who try to spread as much slop for as little money as possible. Slop detection is (I believe) always going to be reasonably easy. Importantly, this is different from the problem of “detecting ambitious cheaters”. Say, imagine you want to win a literary prize or grant proposal. If it costs, say, $10 to bypass Pangram, this is a good deal for you. You ask your AI bot to write the essay or proposal, then spend some money to clean it up until Pangram accepts it as fully human-written. If this is possible, then (2) is just dead, and Pangram can do very little about it. Note that detection of (1) and (2) are very different. (1) is easy. Sloppers are lazy and don’t really care all that much if their content reads as AI. (2) is hard. This is the part where you need to make Pangram resilient against any sufficiently cheap text modification. (1) is just a laziness and inertia situation, (2) is a deep technical problem. The case against Pangram Simple: Pangram has what we’d call a “cursed business model”. As Pangram becomes more successful it will increasingly be used as a quality-gate across the world. Every journal, literary competition or application form will be guarded by Pangram to cut down on low-effort submissions. At this point building an “Anti-Pangram” (aka a “Humanizer” AI model) becomes increasingly profitable until we reach a point at which sufficiently ambitious cheaters will pay some amount of money to “humanize” their texts. On top of this, Pangram’s API can be used against it. You can “just” check if your article passes Pangram’s latest detection model. Sure, this will also cost you some money, but as long as it’s worth it for you, you have nothing to lose. The efficient market and Goodhart’s law should (at this point) manifest with crushing efficiency, and create some sort of “humanizer” competitor that allows bypassing Pangram for anyone who actually cares to. But is this actually going to be the case? Well, honestly probably not? My feeling is that Pangram’s own market should be larger than that of any anti-Pangram competitor. (This is not a trivial argument since cheaters may be willing to spend a lot more money. The question is how expensive it is to build and maintain a competitive humanizer.) This is to say that any company that’s trying to build an anti-Pangram “humanizer” will end up in an arms race against Pangram. Pangram is most likely going to win this race, unless you have enough money (and reason) to fight them on it. No, the real risk that I see here is that of Big AI (Anthropic, OpenAI, Google, possibly others). There’s one competitor which Pangram certainly would not be able to take on, and that’s any of the big AI labs. If they actually cared to train models for “human” output, this should be possible. Well, why aren’t they doing this right now? Oh, they kind of are , but coding capabilities are ten times as important, and pull in a different direction. This is why Claude speaks so weirdly. It’s highly tuned for coding and problem solving. Writing needs to be understandable, but reading like human writers is not nearly as important. In fact, as far as I know Claude’s writing is probabilistically watermarked, and I’d expect all major AI labs to believe that this sort of watermarking may be a mandatory future regulatory requirement (in fact, this is afaik a requirement by the EU AI Act). Even if it’s not, unless they purposefully train the model to be less “predictable” in its writing style, I’d expect Pangram to have a solid edge here. (Side digression: Pangram claims not to use SynthID. I believe them, but I don’t see how it’d be possible to design an “invisible” watermark which Pangram’s own classifier would be unable to detect patterns of during training.) As long as Big AI is in favor of or fine with AI detectors, there is no real risk. If Big AI decided to pull its support, I’d expect Pangram to die pretty quickly. Just raw data and training-wise, whatever Pangram has set up is just not going to be able to compete with any of the really large players here. So, the remaining risks for Pangram’s future are something like: It turns out it’s cheap and easy to build a humanizer, and Pangram will not be able to keep up in the arms race. AI becomes powerful enough to bypass detection if asked or prompted correctly. Whatever makes AI text detectable (watermarking or otherwise) becomes an AI capability training limitation (i.e. disagrees with other AI lab goals). Big AI labs or Clouds start offering their own competitor service to Pangram. (Real risk, but Pangram currently works across “all” labs. Also, this might lead to a Pangram acquisition. Anthropic is offering such an API, currently private. ) 1 and 2 only affect the cheater-catching leg of the business, while sloppers would still be easy to detect. 3 and 4 could also negatively impact slop detection.📝MOND←TECH MAGAZINEWednesday, December 2, 2026
If Microsoft Can Steal FLOSS Code I Can Decomp Fallout New Vegas🎥Zed A. Shaw
OpenGL/C++ No-AI, LSP, or Debugger: Ep29 -- Refactor The Thing🎥Zed A. Shaw
Inside Dario Amodei’s Leaked AI BillPay Your Own Inspector, Hide the Files from FOIA, and Block All 50 States📝My Very Best AI Slop
How to Generate C++ Docs Straight from Clang with MrDocs🎥C++ Alliance
The dialog manager doesn’t remember the resource ID, but that doesn’t stop you from leaving your own breadcrumbsStashing information in a hidden control. The post The dialog manager doesn’t remember the resource ID, but that doesn’t stop you from leaving your own breadcrumbs appeared first on The Old New Thing .📝The Old New Thing
Beyond the Scheduler: Designing Predictable Embedded Systems in Modern C++ - Elbert Dockery - CppCon🎥CppCon
Distributed programming with coroutines and asynchronous communication framework - J. Vanslembrouk🎥MeetingCpp
From Async I/O to Senders and Receivers :: Pavel Šimerda🎥CoreCpp
Moogスタイルラダーフィルターのアナログ的特性をいかに評価するか? - 1ドルクラスのマイクロコントローラー上での検証 - Hiroyuki Oyama - ADC Japan 2026🎥audiodevcon
Advent of μarchitecture Day 2: Pre-decode🎥Matt Godbolt
Why don't NGLAI Bros use AI?🎥Zed A. Shaw
The Rise of TikTokCompanion article to The Personalized Algorithmic Feed fundamentally changed the Web . Feeds have taken over the modern web. How did we get here? The obvious answer is “advertisement money”. I could write about that. I’m sure you’d all vigorously nod along, too. Everyone hates advertisement money. But I have a more interesting question: Why did it take so long for feedscrollers to start dominating the web? TikTok launched internationally in 2017, which is pretty late. Consider: Facebook opened its doors to the public in 2006. Youtube Shorts and Reels launched in 2020. That’s fourteen years between the rise of “the” social network and the first big tech TikTok competitors. TikTok was not the first platform to provide cheap opium for the masses, but it took off like a storm and changed western feedscroller apps for good. Why so late? Why were there no Youtube Shorts in 2007? For reference: Screenshot of 2007 Youtube taken from the 'Version Museum'. Why didn’t they just invent TikTok in the early 2000s, are they stupid? My theory is that they couldn’t, for several reasons. The data wasn’t there. Platforms did not have enough data for deeply personalized algorithms. The platforms did not prioritize data aggregation to the degree they do today. Data science and machine learning wasn’t there. Significant advances happened between the early 2000s and today, including the rise of deep learning. ( Deep Neural Networks for YouTube Recommendations, 2016 ) The content wasn’t there. This was before the content-creator era. We had a fundamental shift in user attitudes between then and now, when content creation became a business, and something anyone could do. The hardware wasn’t there. Phones were still new. People were still on dial-up. Etc. The combination of these factors meant that early personalized algorithmic feeds were not addictive enough . For the modern algorithmic feed to become viable, first an “engagement threshold” had to be crossed. Crossing this threshold required large-scale data aggregation, new research, and the rise of a content-creator culture that just did not exist yet. Hardware limitations are easy enough to measure: The first iPhone released in 2007. No App Store, no ability to record video, and no Google-owned Youtube app yet. Mobile networks (i.e. the ability to watch anywhere you want) also just weren’t there yet. In 2007 only 47% of adult Americans had a broadband connection at home . Mobile users made up 25% of Youtube traffic in 2012, then 50% in 2014 ( Source ). Someone with slightly more time on their hands should run a proper analysis of the data but, roughly speaking, we could guess that anything before 2014 was “too early” for TikTok to really take off. “The Algorithm” TikTok’s crowning achievement was the development of a content-delivery model built for the sake of training data aggregation. Yes, there was an insane amount of debate on TikTok’s algorithm, along with the whole discussion of whether TikTok constitutes a national security risk or is going to kill Youtube entirely, but the algorithm was never that big of a deal in itself. As far as I can tell, what ByteDance did differently is that they started with data aggregation, and then built a video platform around it. Common wisdom dictates that you first build a platform, and then figure out how to aggregate user metrics on top of it. Our modern feedscroller world inverts this. Start with the training data, then build the product. I hate to tell you this, but yes, this is critical start-up advice if you are planning to launch anything at all in the year of our lord 2026. Users are shown one video at a time. Each swipe or tap is new data. If they swipe away, you know that that exact part of the video was not engaging. Videos are short . This ensures users swipe and tap a lot. Better data. TikTok started as a “low-effort” platform. The initial model was “take a video of yourself dancing to music you like”. Everyone can join, all you need is a phone, more data, etc. Data, data, data. Data is what matters. Everyone already knew that, but the rise of TikTok was the last nail in the coffin. The quality of your algorithm and feeds depends on how well-suited it is to extract data from your users.📝MOND←TECH MAGAZINE
How a C++ standard goes through ISO, stage by stageEvery edition of C++ is a separate ISO project with a deadline, and each stage of that project allows different changes. What happens at each stage, who acts in it, how the votes are counted, and why the committee draft is the last stage meant for design comments.📝Train ITTuesday, December 1, 2026
Terrible tips for a C++ developer: 2026 edition, Part 2We're introducing an updated edition of the terrible tips for a C++ developer book. We'll be posting it on our blog in parts. The book includes a total of 60 tips.📝from pvs-studio.com
Addressing AI’s Greatest RisksEven those of us who have spent decades researching AI can be surprised by the capabilities of today's most sophisticated models and the accelerating pace of AI development. These advancements create tremendous opportunities across industries, but they also introduce alarming new threat vectors that are unprecedented in human history. AI models are now so advanced that it seems virtually impossible to predict and control AI behavior, particularly in critical applications.📝Kitware Inc
OpenGL/C++ No-AI, LSP, or Debugger: Ep28 -- Make Thing Anyway🎥Zed A. Shaw
Kitware at the 2026 Beneficial Fire SummitAt this year’s Beneficial Fire Summit, Kitware will connect with prescribed fire practitioners and agencies to discuss how software can support burn documentation and reporting alongside the tools teams already use. The summit brings together people working in prescribed fire, cultural fire, and managed wildfire across California and the West.📝Kitware Inc
Lightning Talk: Building Presentations in slidev - Matt Kulukundis - C++Now 2026🎥CppNow
Why is Windows Explorer displaying a message about a software conflict with Roblox?Deflecting blame onto the process you injected into. The post Why is Windows Explorer displaying a message about a software conflict with Roblox? appeared first on The Old New Thing .📝The Old New Thing
This C++ IDE feature changes everything #cppcon #technology🎥CppCon
Introducing the Qt Widget to Qt Quick Skill: Automating 80% of PortingMoving an existing Qt Widgets user interface to Qt Quick is a big investment. Every screen, dialog, menu and toolbar has to be rebuilt. Every custom-drawn element has to be redesigned. The application logic that sits tangled up with the screens has to be separated out, the project setup has to be reworked, and the result has to be compared with the original screen by screen to make sure nothing was lost. For applications that want a modern, fluid, touch-friendly interface, this adds up to weeks and months of repetitive work that few teams have room for.📝Qt Blog
Processor Design and C++ Memory Models :: Ofek Shilon🎥CoreCpp
Advent of μarchitecture Day 1: Fetch🎥Matt Godbolt
const Integers are special in C++Built-in types are special as they are usable without including anything in C++ or C. In today's post, I like to put the spotlight on int and explore how special an integer is. What's a constant Let me start with this short example: 1 2 3 4 5 6 7 …📝AndreasFertig.comMonday, November 30, 2026
CMake 4.5.1 available for downloadCMake 4.5.1 available for download📝Kitware Inc
OpenGL/C++ with No AI, LSP, or Debugger: Ep27 Maybe One Thing is Wrong🎥Zed A. Shaw
C++ Needs to Catch Up, and FastMemory Safety Won’t Build the Missing Stack📝My Very Best AI Slop
Follow the Anthropic HaloDario Amodei’s $1.5 Trillion Shakedown📝My Very Best AI Slop
C++ Weekly - Ep 561 - emplace_back, initializer_lists, and reserve🎥Jason Turner
Version control is not the same as version numbersOne is a release management problem; the other is a code development problem. The post Version control is not the same as version numbers appeared first on The Old New Thing .📝The Old New Thing
What's New for C++ in Visual Studio Code: C++ & AI Tooling for Your Build, Your Code, Your Workflow🎥CppCon
On Reading Source Code - Patrice Roy - Meeting C++ 2026🎥MeetingCpp
Getting Started With QNX Projects in CLionQNX is a Unix-like real-time operating system used where C and C++ code must be fast, predictable, and maintainable for many years. It powers digital cockpits, medical devices, and robots – from robotic arms on factory lines to autonomous mobile robots in warehouses. Starting with CLion 2026.3.0.3, you can build, deploy, and debug QNX applications […]📝CLion : A Cross-Platform IDE for C and C++ | The JetBrains Blog
C++ Under the Hood: Internal Class Mechanisms :: Chris Ryan🎥CoreCpp
Writing a paper is no longer a signalWhat nobody seems to be discussing is how academic publishing is being disrupted. I am an editor of a well-established journal. Here are the numbers of manuscripts I receive weekly. Writing a science paper used to require massive effort. Highly productive professors might produce 5 solid manuscripts a year. Sure, some publish 30 or 50 … Continue reading Writing a paper is no longer a signal📝Daniel Lemire's blog
C++ Book Review: The Art of Writing Efficient Programs | Modern Cpp Series Ep 255🎥Mike Shah
Processor Design and Memory Models - Ofek Shilon - ACCU 2026🎥ACCUConf
Rust Grows Gradually, It Doesn’t Appear All at Once - Joel Butler - ADC Japan 2026🎥audiodevcon
Building Reality View into Qt Surrounding RealityWhat Tesla Reality View prompted us to build with Qt When Tesla introduced Reality View with Full Self-Driving v15 , the clips circulating online showed a familiar thing from an unfamiliar angle. A virtual camera above the car made the drive visible on the dashboard, with upcoming turns drawn into the scene. The reaction caught our attention and brought a question for cockpit designers into focus. How much of the world around the car helps a driver understand what’s happening? Seeing what the system is tracking can reassure drivers and passengers. It might even spare everyone a round of "Did it see that cyclist?" from the back seat. We responded by adding Reality View to the Qt Surrounding Reality reference design. The first clip shows a recorded drive through reconstructed surroundings, with the car and its overlays rendered in Qt Quick 3D.📝Qt Blog
GSoC 2026: Merging Host and Device ClangIR for Cross-Boundary CUDA/HIP OptimizationHi, I’m David Rivera, a third-year computer science undergrad at Ontario Tech University in Canada. For Google Summer of Code 2026 I worked on the Host-Device CIR Combine Pipeline , mentored by Konstantinos Parasyris (Dinos) and Joseph Huber. I started contributing to ClangIR for the love of the game: I wanted to understand how compilers work underneath. GPU support in ClangIR was limited at the time, so I started working on it, and with the help of the maintainers I became a valuable contributor to the project, especially on the components related to GPU compilation. This project started as Dinos’s idea. He had a work-in-progress merge pipeline in the ClangIR incubator, and in January I added the driver-side support for CUDA on top of his branch. Before GSoC I also spent months landing CUDA and HIP support upstream ( tracking issue ), which this project depends on and which is like another mini GSoC project by itself. GSoC took me from sending patches to coordinating with the community: contributing to an RFC, publishing our evaluations and prototypes, writing my first paper, which will appear at LLVM-HPC at SC26 , and attending my first LLVM Developers’ Meeting. I also got to meet in person the maintainers I’d only interacted with through code review, which was a really cool experience. TL;DR: We have a prototype that merges the host and device ClangIR modules of a CUDA or HIP translation unit into one module, runs passes that see both sides, and splits them back into the normal pipelines. We’ve measured real benefits with it. We implemented three optimizations on top of it: kernel argument constant propagation, launch bounds propagation, and alias information forwarded from host launch sites. Alias information provides by far the largest gains: a 1.67× geomean in GPU-region time on PolyBench/GPU on an NVIDIA A10, with caveats I go through below. The prototype isn’t merged upstream yet. The foundations have landed, including the container and the work that followed Dinos’s RFC , we have a roadmap for the rest, and we’ll be working on it in the coming months. Background Clang compiles a CUDA or HIP translation unit several times: one host cc1 , plus one device cc1 per GPU architecture. There is never a single phase in the compiler where we have visibility of both the host launches and the kernels they launch, so co-optimizing them isn’t possible. Here’s what that costs: __global__ void acc ( float * out, const float * a, const float * b, int n) { int tid = blockIdx.x * blockDim.x + threadIdx.x; if (tid n) out[tid] = a[tid] + b[tid]; } int main () { // ... cudaMalloc(( void ** ) & a, bytes); cudaMalloc(( void ** ) & b, bytes); cudaMalloc(( void ** ) & out, bytes); acc (n + 255 ) / 256 , 256 >>> (out, a, b, n); } Anyone reading this can see that out , a and b are three separate buffers. The device compilation can’t: it only has the kernel, so it has to assume out may overlap a or b . We can’t just compile everything once, because headers can branch on __CUDA_ARCH__ , so parsing and Sema have to run once per side. What we can do is bring the two sides together after that step. Giving the compiler one view of both sides isn’t a new idea. The Heterogeneous LLVM-IR Modules RFC from 2020 sought the same visibility, but a conventional LLVM module has one target and one data layout. MLIR modules nest and each can carry its own, and ClangIR (CIR) is the bridge that gets a Clang AST into MLIR, with LLVM and the target backends still downstream. Since CIR comes after Sema, each side contributes its own correct translation and we merge those. Getting CUDA and HIP through CIR first None of this works if CIR can’t compile the programs in the first place, so a lot of my time went into parity: calling conventions, kernel registration, NVPTX builtins, address spaces and function attributes. In August, across 21 PolyBench/GPU programs, CIR matched classic CodeGen at 0.998× runtime on an H100 and 1.008× on an MI300X, with about 3% more compile time ( raw data ). We wrote up this part of the work, how CUDA and HIP kernels lower through CIR, in the paper that will appear at SC26. 25 of my PRs merged upstream during the project, and they’re listed at the end of this post. The merge pipeline The prototype lives on my fork. With --clangir-offload-merge , the driver stops each compilation after CIR, merges the results, runs the cross-boundary passes, splits the module back apart and resumes each cc1 from CIR: clang -x cuda -fclangir --clangir-offload-merge --cuda-gpu-arch = sm_86 -c kernel.cu clang -x hip -fclangir --clangir-offload-merge --offload-arch = gfx942 -c kernel.hip Two new job actions, CIRMergeJobAction and CIRSplitJobAction , both map to a standalone tool, cir-offload-merge . You can also run the steps by hand: cir-offload-merge -combine \ -input = host.cir -input = device-sm86.cir \ -targets = host-x86_64-unknown-linux-gnu,cuda-nvptx64-nvidia-cuda--sm_86 \ -output = combined.cir This works for CUDA and HIP, with one or several GPU architectures. The container The merged module is an ordinary MLIR module with host and device modules nested inside it. Trimmed: module attributes {cir.offload.container} { module @host attributes {cir.offload.kind = #cir.offload_kind } { // stubs + launch sites } module @device_cuda_nvptx64_nvidia_cuda__sm_86 attributes {cir.offload.kind = #cir.offload_kind } { // kernels, cc(ptx_kernel) } } My first version was a dedicated cir.offload.container op, because I wanted the verifier to enforce the hierarchy: one host module, then one or more device modules. In review of #206576 , Andy Kaylor asked whether we needed the op at all, or whether a module marked with an attribute could be the container. Looking at how the gpu dialect verifies gpu.container_module , I could keep the same invariants in CIRDialect::verifyOperationAttribute without introducing a new op, so that’s what landed. Connecting launches to kernels Being in the same module doesn’t connect anything, because a launch never calls the kernel directly. It goes through a stub and the runtime: // acc >>(out, a, b, n) lowers to: __cudaPushCallConfiguration(grid, block); __device_stub__acc(out, a, b, n); // and the stub, generated by Clang: void __device_stub__acc (...) { void * args[] = { & out, ...}; cudaLaunchKernel(( void * )__device_stub__acc, grid, block, args); } The link between the stub and the kernel only exists at runtime, through __cudaRegisterFunction . So the first analysis I wrote, KernelBindingTable , recovers that mapping statically: each host stub, its device kernel in each architecture’s module, and every launch site with its arguments and grid and block geometry. Every pass below is built on it. Reflecting on the implementation, we believe this mapping should be an operation in the IR rather than an analysis, which I come back to under future work. What made this harder than it looks Resuming from .cir . The pipeline has to re-enter cc1 with CIR as input and no ASTContext , so anything the later stages used to read from the AST has to live on the module. Dinos led the upstream work on this, starting from an RFC and tracked in #227917 . Lowering .cir input to objects landed in October ( #232506 ), and stopping before ABI lowering is still open. One context for two targets. Combining parses every input into a single MLIRContext , and CIR records are uniqued by name, so a different body for the same name on the device side is silently dropped. Valid code hits this: a host-only lambda shifts CIRGen’s anon.N counter, so the names stop matching. I have a prototype fix that namespaces device records on a separate branch . The first passes, and what moved runtime We started with a couple of passes that were partly a concept of how cross-boundary optimization could work: Pass What it does Runtime result Kernel argument constant propagation Folds an argument into the kernel when every launch passes the same constant Neutral on its own (1.0016× at 1× size, 0.9996× at 2×), but binaries were 11.8% smaller Launch bounds propagation Records the largest constant block size as nvvm.maxntid , like a user-written __launch_bounds__ 0.9998× geomean, and the SASS (NVIDIA’s machine code) was byte-identical on all 21 programs We expected launch bounds to be the biggest early win, since PolyBench declares its block sizes statically. On this suite the hint is invariant, and the reason is useful. NVPTX has no register allocator in LLVM, so ptxas makes the real decisions, and maxntid only gives it room to use more registers per thread. These kernels don’t spill registers to memory, so that room has nothing to relieve. The HeCBench kernels we forced by hand with stock nvcc were register-lean as well and showed the same result. We expect kernels with higher register pressure, the ones that actually spill, to benefit from this optimization, and we still need to widen our search for candidates like that. The pass only runs for NVIDIA today. Experimenting with AMD is something we still have to do, and we’re aware we might see different results on AMD or on Intel targets, although Intel isn’t something we support here. So by early September the infrastructure worked and nothing was faster. At our sync that week, Dinos suggested looking at aliasing: the host sees facts about buffers, and it could attach metadata like noalias . Andy had just added the start of alias analysis to CIR upstream. After launch bounds, I wanted to know whether the fact could matter before writing a pass for it. I injected __restrict by hand on the kernel pointers of 2mm , 3mm , gemm and gramschmidt and compiled with classic CodeGen, with no CIR involved. I wrote the rule down first: if the SASS stayed identical on all 9 kernels, we wouldn’t build the pass. It changed on all four programs, and kernel-region time came out about 2.3× faster on 2mm , 3mm and gramschmidt and 1.9× on gemm , with identical checksums. The remaining question was whether the compiler could prove what I’d written by hand. Launch-derived noalias The OffloadPointerFacts pass ( #30 ) starts from the acc example at the top of this post. For each kernel, it uses the binding table to look at every visible launch and checks that: every launch is known, each pointer argument traces to a different live cudaMalloc , and the kernel can’t reach those buffers any other way: no address-taken global, loaded pointer, escape or in-kernel allocation. If all of that holds, the existing kernel parameters get llvm.noalias : cir. func @_Z3accPfPKfS1_i (%out: !cir.ptr {llvm.noalias}, %a: !cir.ptr {llvm.noalias}, %b: !cir.ptr {llvm.noalias}, %n: !s32i) cc(ptx_kernel) The proof is kernel-wide and conservative: a repeated allocation, an unprovable argument or an unprovable path through the body drops every annotation on that kernel. My first version got this wrong, and review caught it. Dinos pointed out that I never proved the allocation reaches the launch. I only checked the order of stores, so this got noalias : float * A = B; if (c) cudaMalloc( & A, n); // skipped when !c k 1 , 1 >>> (A, B); // A == B The allocation now has to dominate the launch. He also showed a pointer smuggled through a uintptr_t argument, and a __noinline__ callee writing to a buffer through a device global. In the end, callees are checked with the same rules as the kernel, and later rounds of review from Dinos and Steffen Larsen turned the body check into an allow-list of pointer sources and made inline asm a rejection. The pass only adds attributes, and unchanged LLVM passes do the optimizing. Here’s PolyBench gemm at -O3 for sm_86 , trimmed, with index math and unrolling removed: ; before: c may alias a or b loop: %acc = phi float [ %c0, %pre ], [ %sum, %loop ] %va = load float , ptr %a.ik %vb = load float , ptr %b.kj %p = fmul float (%alpha * %va), %vb %sum = fadd float %acc, %p store float %sum, ptr %c.ij ; every iteration br i1 %done, label %exit, label %loop ; after: noalias from the host loop: %acc = phi float [ %c0, %pre ], [ %sum, %loop ] %va = load float , ptr %a.ik %vb = load float , ptr %b.kj %p = fmul float (%alpha * %va), %vb %sum = fadd float %acc, %p br i1 %done, label %exit, label %loop exit: store float %sum, ptr %c.ij ; once The sum was already in a register before the change. The store only stayed in the loop because the next load might read c . With the fact in place, LICM’s store promotion sinks it, taking the kernel from 6 stores to 2. Turning that off with -disable-licm-promotion brings all 6 back. The NVPTX backend also gets to use the non-coherent load form: 10 of the 11 global loads become ld.global.nc , and the remaining one is c , which is written. This pattern, accumulating inside a loop while alias uncertainty pins the memory access, is the one I kept seeing across the suite. Results Pass on versus pass off on an NVIDIA A10 ( sm_86 ), with everything else identical: 3 warmup runs plus 8 samples, serial, using the benchmark’s own GPU-region timer. These were measured at fbda065af219 , a revision that predates the final rounds of review. Validation passed in all 42 records across the two arms. Benchmark Speedup Benchmark Speedup correlation 7.17× gemm 1.90× covariance 7.08× atax 1.79× bicg 2.37× mvt 1.78× 2mm 2.28× gesummv 1.29× 3mm 2.26× syrk 1.07× gramschmidt 2.24× syr2k 1.03× gemver 2.05× adi 1.02× doitgen 2.03× The other six stay within about 1.5% of 1.00×, with jacobi-2d the lowest at 0.985×. Geomean over all 21 is 1.67× , and compile time goes up by 0.006 s per benchmark. These are the numbers I posted on Discourse and on #30 . That table only covers GPU-region time. I also compared the whole merge pipeline against the same -O3 CIR compilation without it, including wall time for the whole process: Problem size GPU-region speedup Wall-time speedup 1× 1.72× 1.19× 2× 1.68× 1.24× 4× 1.64× 1.25× The wall-time gain is smaller because GPU work is only part of the process. This run used an earlier revision of the pipeline at 7a94fd56356d and covers 20 programs. The 4× run was timing-only on a different A10. #30 has the details. Please read those numbers with these in mind: The kernels were forced static . If a kernel’s host stub is externally visible, another object could launch it, so the pass correctly leaves it alone. I patched the suite to make the kernels internal, which isn’t what you’d get on the suite as shipped. PolyBench is a starting point. These are single-file programs with flat kernels and small call graphs. Future work is to experiment deeper on large applications, catch the transformations that could yield better benefits there, and measure compile time on them too. 7× isn’t typical. In the whole-pipeline run, correlation and covariance dropped to about 4.6× at 4× problem size. One GPU, one vendor. The pass only recognizes cudaMalloc today, so these are CUDA numbers. The pipeline runs for HIP, but this pass doesn’t fire there on the final branch. HeCBench and other benchmarks Forcing static on every kernel isn’t an option for real code. Steffen contributed kernel cloning helpers that create a specialized copy of a kernel for a chosen set of launches and always keep the original, since the runtime can still reach it by name. A separate branch builds on them, so proven launches get an internal clone that carries the facts. That’s crucial for not having to write static all the time, and it’s what let us explore much more complex benchmarks. On the four unmodified PolyBench programs I ran, the gains mostly hold: 2mm 2.26×, 3mm 2.18×, gemm 1.81×, and lu 0.997× as a control. On HeCBench , the pass fires much less often and the gains are smaller: Benchmark Speedup Note chemv 1.75× Kernel pulled into the host TU with -include ; binary grows from 25.7 KB to 38.1 KB softmax 1.05× Stock source; loads become the read-only form miniFE, CG iteration 1.016× matvec inlined by hand; only 1 of 11 kernels is cloned To see how far this could go, I also forced noalias on every kernel pointer in IR, locally with stand-in headers, which gives an upper bound. Across 1,152 HeCBench kernels, stores or loops went down in 11. The accumulate-through-a-buffer pattern is less common there: a source scan finds it in 24 of 1,427 kernels, against 24 of 47 in PolyBench. In Rodinia’s 78 kernels, none lost a loop or a store from an innermost loop. When the pass doesn’t fire on real code, these are the main reasons: What blocks the pass Where we saw it Allocation and launch live in different functions 17 of 46 failed allocation traces in one HeCBench survey, plus miniFE Kernel defined in one file, declared in a header and launched from another 41 of 164 HeCBench benchmarks, including chemv cudaMalloc inside a nested scope, like an error-check macro About 77 of 519 HeCBench benchmarks Two buffers swapped between launches 14 HeCBench benchmarks, by source search Kernel passes a buffer pointer to a helper LULESH and 6 other HeCBench benchmarks Buffers owned by a framework object darknet, where forcing noalias takes the average pooling kernel from 67 SASS stores to 1, but none of the 48 launch sites we checked can be traced So the PolyBench numbers don’t carry over to real code today. The pattern is less common there, and when it’s present, the pass often can’t prove the facts. Limitations Separate TUs hide definitions. We merge one TU at a time, so a launch of a kernel defined in another TU only sees a declaration. The pipeline is also non-RDC only, so a device function calling a device function in another TU isn’t covered either. Solving this needs visibility across translation units, which is an inherent problem in compilers, not one specific to this pipeline. Tracing facts across the boundary is hard. When the launch sits in a function and the allocation happens in its caller, we can’t walk back and see every allocation, so the kernel gets rejected. A proper interprocedural framework would help more than another pass. Specialization has a cost. Cloning grows the binary, as chemv shows, so a cost model that decides when a clone is worth it would be great, and looking at what LLVM does for specialization is a good starting point. Status and future work Piece Status Container attribute and verifier Upstream ( #206576 ) Emitting and resuming .cir through cc1 Upstream, stop point before ABI lowering still open Driver integration, cir-offload-merge , binding table, passes Fork, on gsoc/combine-cir I’m staying on this after GSoC, and I’m planning to upstream all of these findings. The bigger goal is a much more generic representation of GPU programs in CIR, one that works across different GPU targets and runtimes: Launches connected through the call graph. KernelBindingTable is a proof of concept, and it’s one of the parts we likely need to reassess. MLIR has generic transformations like symbol-dce and sccp that dialects opt into through interfaces, and we could rely on them if a launch connected the call graph on the host to the kernel on the device. A higher-level launch op, similar to what the gpu dialect has, would make that edge explicit in the IR. This was also some of the feedback we got at the LLVM Developers’ Meeting. Generic runtime operations. The noalias pass has to recognize cudaMalloc , and with today’s shape we’d have to track every runtime’s allocation, whether that’s CUDA, HIP, liboffload or anything else. Ideally these operations would be generic in the CIR dialect, which is in part what the gpu dialect does. This representation can also introduce new diagnostics, because it sees both sides of the program. A small prototype warns when a kernel argument’s layout differs between host and device. I think the combine tool has a lot of potential, and conversations at the meeting with people from several important vendors in the space backed that up. I believe it’s one of the reasons someone would want to use ClangIR in the first place. Steffen also continues to help upstream and on the fork, and Mariya Podchishchaeva mainly upstream. What I learned The biggest surprise was how much alias analysis gave us. Initially our optimizations were a bit shallow: we went from constant propagation to launch bounds, and neither caused a noticeable speedup on PolyBench. I was sort of expecting aliasing to unlock something, since I’ve read a couple of LLVM’s middle-end passes and it’s one of the things that blocks many of them, but not at the level it did on PolyBench. The other thing I really learned is how to evaluate whether a pass is worth chasing. What I mainly did was inject the information a pass could derive, either from the front end or into LLVM IR, and check whether later passes consume it and whether SASS ultimately benefits. That’s far less work than the pass. Acknowledgements Thanks to my mentors, Dinos Parasyris and Joseph Huber, and especially to Dinos, whose idea this was and who I’ve been working with on CUDA support in CIR since January. Thanks to Steffen Larsen (AMD), who was working on a similar staging layer, reached out, and ended up contributing #27 , #28 , #31 and #32 to the fork. Thanks to the ClangIR maintainers Bruno Cardoso Lopes, Andy Kaylor, Erich Keane and Henrich Lauko for their reviews, and to Mariya Podchishchaeva for her upstream work on CIR. Thanks also to Google and the LLVM community for making GSoC possible. Links Final work: gsoc/combine-cir Talk: CUDA and HIP in ClangIR , LLVM Offload Workshop, Santa Clara, October 2026 Paper: GPU Device Compilation in ClangIR: Lowering CUDA and HIP Kernels Through the CIR Pipeline , with Bruno Cardoso Lopes, Joseph Huber and Dinos Parasyris, LLVM-HPC 2026 at SC26, November 16 Benchmark harness: polybench-gpu-audit Upstream PRs merged during the project: Area PRs Offload container #206576 CUDA/HIP codegen #195381 , #195382 , #195391 , #199270 , #204663 , #215314 , #231390 NVPTX builtins and attributes #195214 , #195217 , #214708 , #216447 , #221255 , #221261 , #221262 Address spaces #196868 , #226649 , #226650 Aliasing and floating point #221817 , #221818 , #226334 Tooling #196245 , #200266 , #229565 , #229575 Fork PRs are on RiverDave/llvm-project .📝The LLVM Project Blog
Pattern Matching for C++29Update from Búzios, a tour of P2688R6, and next steps📝Michael Park
How overload resolution picks one functionCopying a non-const int_or_empty gives a non-empty object because a forwarding constructor is a better match than the copy constructor, while copying a const one and moving one both work. How C++ ranks the candidates, which tie-breakers apply and in what order, and how to constrain the template so it leaves copies to the copy constructor.📝Train IT