Skip to content

File System Helpers (filesystem.h)

Chris Guzak edited this page Dec 10, 2023 · 3 revisions

CreateFileW helpers

Simpler use of CreateFileW enabled with default parameters. Functions named to describe the behavior of the flags that control the behavior.

auto handle = wil::open_file(path.c_str());

The design uses "open", "create" and "truncate" to distinguish the cases that open existing files and use that creates and modifies existing files. Here is more complicated use that demonstrates the handle and error code being returned (used in success cases, so providing access to it is essential.).

auto path = wil::ExpandEnvironmentStringsW<std::wstring>(LR"(%TEMP%\create_file_test.txt)");
auto [fileHandle, error] = wil::try_create_new_file(path.c_str())

Here, are the method names that describe the semantics.

auto handle = wil::create_new_file(path.c_str());
auto handle = wil::open_or_create_file(path.c_str());
auto handle = wil::open_or_truncate_existing_file(path.c_str());
auto handle = wil::truncate_existing_file(path.c_str());

Folder Change Reader

Observe changes in a folder system including the specific changes using the Win32 API ReadDirectoryChangesW

#include <wil/filesystem.h>

auto reader = wil::make_folder_change_reader(folder.Path().c_str(), true, wil::FolderChangeEvents::All,
    [](wil::FolderChangeEvent event, PCWSTR fileName)
    {
         switch (event)
         {
         case wil::FolderChangeEvent::ChangesLost: break;
         case wil::FolderChangeEvent::Added:    break;
         case wil::FolderChangeEvent::Removed:  break;
         case wil::FolderChangeEvent::Modified: break;
         case wil::FolderChangeEvent::RenamedOldName: break;
         case wil::FolderChangeEvent::RenamedNewName: break;
     });

Folder Watcher

Observe changes to the file system using the Win32 API FindFirstChangeNotificationW

#include <wil/filesystem.h>

auto watcher = wil::make_folder_watcher(folder.Path().c_str(), true, wil::allChangeEvents, []()
    {
        // respond
    });

File Information

Get information about a file from an open handle.

auto basicInfo = wil::GetFileInfo<FileBasicInfo>(fileHandle);

Create Directory

Create a directory including the intermediate path segments.

wil::CreateDirectoryDeepNoThrow(LR"(C:\temp\folder)");

Remove Directory

Delete a folder including its contents and sub-folders.

wil::RemoveDirectoryRecursive(LR"(c:\temp)", RemoveDirectoryOptions::RemoveReadOnly);