Sane C++ Libraries
C++ Platform Abstraction Libraries
Loading...
Searching...
No Matches
FileSystem.h
1// Copyright (c) Stefano Cristiano
2// SPDX-License-Identifier: MIT
3#pragma once
4#include "../Foundation/Internal/IGrowableBuffer.h"
5#include "../Foundation/PrimitiveTypes.h"
6#include "../Foundation/Result.h"
7#include "../Foundation/StringPath.h"
8
9namespace SC
10{
13
16
19{
20 Unknown,
21 File,
22 Directory,
23 SymbolicLink,
24 Other,
25};
26
58
61{
62 Exists,
63 Read,
64 Write,
65 Execute,
66};
67
70{
72 {
73 overwrite = false;
75 }
76
81 {
82 overwrite = value;
83 return *this;
84 }
85
90 {
91 useCloneIfSupported = value;
92 return *this;
93 }
94
95 bool overwrite;
97};
98
105struct SC_COMPILER_EXPORT FileSystem
106{
107 bool preciseErrorMessages = false;
108
111
115 Result init(StringSpan initialDirectory);
116
121
124
132
140
149 Result copyFile(StringSpan source, StringSpan destination, CopyFlags copyFlags = CopyFlags())
150 {
151 return copyFiles(CopyOperation{source, destination, copyFlags});
152 }
153
159
168 Result copyDirectory(StringSpan source, StringSpan destination, CopyFlags copyFlags = CopyFlags())
169 {
170 return copyDirectories(CopyOperation{source, destination, copyFlags});
171 }
172
182
187
192 Result removeFile(StringSpan source) { return removeFiles({source}); }
193
198
203
209
216 Result removeDirectoryRecursive(StringSpan directory) { return removeDirectoriesRecursive({directory}); }
217
223
228 Result removeEmptyDirectory(StringSpan directory) { return removeEmptyDirectories({directory}); }
229
235
240 Result makeDirectory(StringSpan directory) { return makeDirectories({directory}); }
241
246
250 Result makeDirectoryIfNotExists(StringSpan directory) { return makeDirectoriesIfNotExists({directory}); }
251
257
262 Result makeDirectoryRecursive(StringSpan directory) { return makeDirectoriesRecursive({directory}); }
263
268 Result createSymbolicLink(StringSpan sourceFileOrDirectory, StringSpan linkFile);
269
275
280 [[nodiscard]] bool exists(StringSpan fileOrDirectory);
281
285 [[nodiscard]] bool existsAndIsDirectory(StringSpan directory);
286
293 [[nodiscard]] bool existsAndIsFile(StringSpan file);
294
298 [[nodiscard]] bool existsAndIsLink(StringSpan file);
299
304 [[nodiscard]] bool canAccess(StringSpan fileOrDirectory, AccessMode accessMode = AccessMode::Exists);
305
310 [[nodiscard]] bool moveDirectory(StringSpan sourceDirectory, StringSpan destinationDirectory);
311
320 Result write(StringSpan file, Span<const uint8_t> data);
321
328
334
340 template <typename T>
341 Result read(StringSpan file, T& data)
342 {
343 return read(file, GrowableBuffer<T>{data});
344 }
345
350 Result read(StringSpan file, IGrowableBuffer&& buffer);
351
354
359 Result stat(StringSpan file, FileStat& fileStat);
360
365 Result lstat(StringSpan file, FileStat& fileStat);
366
372
378
384
391
398
404
410
413 struct SC_COMPILER_EXPORT Operations
414 {
415 static Result access(StringSpan path, AccessMode accessMode);
416 static Result createSymbolicLink(StringSpan sourceFileOrDirectory, StringSpan linkFile);
417 static Result createHardLink(StringSpan sourceFile, StringSpan linkFile);
418 static Result makeDirectory(StringSpan dir);
419 static Result exists(StringSpan path);
420 static Result existsAndIsDirectory(StringSpan path);
421 static Result existsAndIsFile(StringSpan path);
422 static Result existsAndIsLink(StringSpan path);
423 static Result makeDirectoryRecursive(StringSpan path);
424 static Result removeEmptyDirectory(StringSpan path);
425 static Result moveDirectory(StringSpan source, StringSpan destination);
426 static Result removeFile(StringSpan path);
427 static Result copyFile(StringSpan srcPath, StringSpan destPath, FileSystemCopyFlags flags);
428 static Result rename(StringSpan path, StringSpan newPath);
429 static Result copyDirectory(StringSpan srcPath, StringSpan destPath, FileSystemCopyFlags flags);
430 static Result removeDirectoryRecursive(StringSpan directory);
431 static Result stat(StringSpan path, FileSystemStat& fileStat);
432 static Result lstat(StringSpan path, FileSystemStat& fileStat);
433 static Result getFileStat(StringSpan path, FileSystemStat& fileStat);
434 static Result readSymbolicLink(StringSpan path, StringPath& destination);
435 static Result chmod(StringSpan path, uint32_t mode);
436 static Result chown(StringSpan path, uint32_t uid, uint32_t gid);
437 static Result lchown(StringSpan path, uint32_t uid, uint32_t gid);
438 static Result lchmod(StringSpan path, uint32_t mode);
439 static Result setLastModifiedTime(StringSpan path, TimeMs time);
440
441 static StringSpan getExecutablePath(StringPath& executablePath);
442 static StringSpan getCurrentWorkingDirectory(StringPath& currentWorkingDirectory);
443 static StringSpan getApplicationRootDirectory(StringPath& applicationRootDirectory);
444
445 private:
446 struct Internal;
447 };
448
449 private:
450 [[nodiscard]] bool convert(const StringSpan file, StringPath& destination, StringSpan* encodedPath = nullptr);
451
452 StringPath fileFormatBuffer1;
453 StringPath fileFormatBuffer2;
454 StringPath currentDirectory;
455
456 char errorMessageBuffer[256] = {0};
457
458 Result formatError(int errorNumber, StringSpan item, bool isWindowsNativeError);
459 struct Internal;
460};
462} // namespace SC
FileSystemAccessMode
Access mode for path checks.
Definition FileSystem.h:61
FileSystemEntryType
A structure to describe file stats.
Definition FileSystem.h:19
@ Write
Check if path is writable.
@ Exists
Check if path exists.
@ Execute
Check if path is executable / traversable.
@ Read
Check if path is readable.
unsigned char uint8_t
Platform independent (1) byte unsigned int.
Definition PrimitiveTypes.h:36
unsigned long long uint64_t
Platform independent (8) bytes unsigned int.
Definition PrimitiveTypes.h:42
unsigned int uint32_t
Platform independent (4) bytes unsigned int.
Definition PrimitiveTypes.h:38
A structure to describe copy flags.
Definition FileSystem.h:70
FileSystemCopyFlags & setUseCloneIfSupported(bool value)
If true copy will use native filesystem clone os api.
Definition FileSystem.h:89
FileSystemCopyFlags & setOverwrite(bool value)
If true copy will overwrite existing files in the destination.
Definition FileSystem.h:80
bool useCloneIfSupported
If true copy will use native filesystem clone os api.
Definition FileSystem.h:96
bool overwrite
If true copy will overwrite existing files in the destination.
Definition FileSystem.h:95
A structure to describe file stats.
Definition FileSystem.h:29
uint32_t mode
POSIX st_mode.
Definition FileSystem.h:40
uint32_t reparseTag
Windows reparse tag.
Definition FileSystem.h:53
size_t hardLinkCount
Number of hard links to the entry.
Definition FileSystem.h:33
TimeMs accessedTime
Time when file was last accessed when available.
Definition FileSystem.h:35
TimeMs creationTime
Time when file was created when available.
Definition FileSystem.h:34
uint64_t blockSize
POSIX st_blksize.
Definition FileSystem.h:47
FileSystemEntryType entryType
Type of entry stored at path.
Definition FileSystem.h:30
size_t fileSize
Size of the file in bytes.
Definition FileSystem.h:32
uint64_t blocks
POSIX st_blocks.
Definition FileSystem.h:46
uint32_t gid
POSIX st_gid.
Definition FileSystem.h:42
uint64_t inode
POSIX st_ino.
Definition FileSystem.h:43
uint64_t fileIndex
Windows file index.
Definition FileSystem.h:55
uint64_t specialDevice
POSIX st_rdev.
Definition FileSystem.h:45
uint32_t uid
POSIX st_uid.
Definition FileSystem.h:41
TimeMs modifiedTime
Time when file was last modified.
Definition FileSystem.h:36
uint32_t volumeSerialNumber
Windows volume serial number.
Definition FileSystem.h:54
uint64_t device
POSIX st_dev.
Definition FileSystem.h:44
uint32_t attributes
Windows file attributes.
Definition FileSystem.h:52
Specify source, destination and flags for a copy operation.
Definition FileSystem.h:127
StringSpan destination
Copy operation sink (can be a {relative | absolute} {file | directory} path)
Definition FileSystem.h:129
CopyFlags copyFlags
Copy operation flags (overwrite, use clone api etc.)
Definition FileSystem.h:130
StringSpan source
Copy operation source (can be a {relative | absolute} {file | directory} path)
Definition FileSystem.h:128
Low level filesystem API, requiring paths in native encoding (UTF-16 on Windows, UTF-8 elsewhere)
Definition FileSystem.h:414
Execute fs operations { exists, copy, delete } for { files and directories }.
Definition FileSystem.h:106
bool existsAndIsFile(StringSpan file)
Check if a file exists at given path.
Result removeFiles(Span< const StringSpan > files)
Remove multiple files.
Result removeFile(StringSpan source)
Remove a single file.
Definition FileSystem.h:192
Result lstat(StringSpan file, FileStat &fileStat)
Obtains richer metadata about a path without following symbolic links.
Result chown(StringSpan path, uint32_t uid, uint32_t gid)
Change owner and group for a path, following symbolic links.
Result readSymbolicLink(StringSpan linkFile, StringPath &destination)
Reads the target path stored by a symbolic link.
Result init(StringSpan initialDirectory)
Call init function when instantiating the class to set directory for all operations using relative pa...
Result read(StringSpan file, T &data)
Read contents of a file into a String or Buffer.
Definition FileSystem.h:341
Result changeDirectory(StringSpan newDirectory)
Changes current directory.
Result makeDirectoriesRecursive(Span< const StringSpan > directories)
Create new directories, creating also intermediate non existing directories (like posix mkdir -p)
Result removeLinkIfExists(StringSpan source)
Remove a single link, giving no error if it doesn't exist.
bool exists(StringSpan fileOrDirectory)
Check if a file or directory exists at a given path.
bool moveDirectory(StringSpan sourceDirectory, StringSpan destinationDirectory)
Moves a directory from source to destination.
Result removeDirectoriesRecursive(Span< const StringSpan > directories)
Remove multiple directories with their entire content (like posix rm -rf)
Result setLastModifiedTime(StringSpan file, TimeMs time)
Change last modified time of a given file.
Result copyFiles(Span< const CopyOperation > sourceDestination)
Copies many files.
Result lchown(StringSpan path, uint32_t uid, uint32_t gid)
Change owner and group for a path without following symbolic links.
Result removeEmptyDirectories(Span< const StringSpan > directories)
Removes multiple empty directories.
Result makeDirectoryRecursive(StringSpan directory)
Create a new directory, creating also intermediate non existing directories (like posix mkdir -p)
Definition FileSystem.h:262
bool existsAndIsDirectory(StringSpan directory)
Check if a directory exists at given path.
Result writeStringAppend(StringSpan file, StringSpan text)
Appends a StringSpan to a file.
Result getFileStat(StringSpan file, FileStat &fileStat)
Legacy convenience alias for stat(StringSpan, FileStat&)
Result removeFileIfExists(StringSpan source)
Remove a single file, giving no error if it doesn't exist.
Result stat(StringSpan file, FileStat &fileStat)
Obtains richer metadata about a path, following symbolic links.
Result rename(StringSpan path, StringSpan newPath)
Rename a file or directory.
Result makeDirectory(StringSpan directory)
Creates a new directory that does not already exist.
Definition FileSystem.h:240
Result removeDirectoryRecursive(StringSpan directory)
Remove single directory with its entire content (like posix rm -rf)
Definition FileSystem.h:216
Result makeDirectories(Span< const StringSpan > directories)
Creates new directories that do not already exist.
Result chmod(StringSpan path, uint32_t mode)
Change file permission bits for a path, following symbolic links.
Result write(StringSpan file, Span< const char > data)
Writes a block of memory to a file.
Result read(StringSpan file, IGrowableBuffer &&buffer)
Read contents of a file into an IGrowableBuffer.
Result makeDirectoriesIfNotExists(Span< const StringSpan > directories)
Creates new directories, if they don't already exist at the given path.
Result copyDirectory(StringSpan source, StringSpan destination, CopyFlags copyFlags=CopyFlags())
Copy a single directory.
Definition FileSystem.h:168
Result createHardLink(StringSpan sourceFile, StringSpan linkFile)
Creates a hard link at location linkFile pointing at sourceFile.
Result createSymbolicLink(StringSpan sourceFileOrDirectory, StringSpan linkFile)
Creates a symbolic link at location linkFile pointing at sourceFileOrDirectory.
bool canAccess(StringSpan fileOrDirectory, AccessMode accessMode=AccessMode::Exists)
Check whether the current process can access a path with the requested mode.
Result copyDirectories(Span< const CopyOperation > sourceDestination)
Copy many directories.
Result copyFile(StringSpan source, StringSpan destination, CopyFlags copyFlags=CopyFlags())
Copy a single file.
Definition FileSystem.h:149
Result lchmod(StringSpan path, uint32_t mode)
Change file permission bits for a symbolic link without following it.
Result makeDirectoryIfNotExists(StringSpan directory)
Creates a new directory, if it doesn't already exists at the given path.
Definition FileSystem.h:250
Result removeEmptyDirectory(StringSpan directory)
Removes an empty directory.
Definition FileSystem.h:228
bool existsAndIsLink(StringSpan file)
Check if a link exists at given path.
Result writeString(StringSpan file, StringSpan text)
Replace the entire content of a file with the provided StringSpan.
An ascii string used as boolean result. SC_TRY macro forwards errors to caller.
Definition Result.h:13
View over a contiguous sequence of items (pointer + size in elements).
Definition Span.h:29
Pre-sized char array holding enough space to represent a file system path.
Definition StringPath.h:42
An read-only view over a string (to avoid including Strings library when parsing is not needed).
Definition StringSpan.h:37
A vocabulary type representing a time interval in milliseconds since epoch.
Definition PrimitiveTypes.h:63