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/Compiler.h"
5#ifndef SC_EXPORT_LIBRARY_FILE_SYSTEM
6#define SC_EXPORT_LIBRARY_FILE_SYSTEM 0
7#endif
8#define SC_FILE_SYSTEM_EXPORT SC_COMPILER_LIBRARY_EXPORT(SC_EXPORT_LIBRARY_FILE_SYSTEM)
9
10#include "../Foundation/Internal/IGrowableBuffer.h"
11#include "../Foundation/PrimitiveTypes.h"
12#include "../Foundation/Result.h"
13#include "../Foundation/StringPath.h"
14
15namespace SC
16{
19
22
25{
26 Unknown,
27 File,
28 Directory,
29 SymbolicLink,
30 Other,
31};
32
64
67{
68 Exists,
69 Read,
70 Write,
71 Execute,
72};
73
76{
78 {
79 overwrite = false;
81 }
82
87 {
88 overwrite = value;
89 return *this;
90 }
91
96 {
97 useCloneIfSupported = value;
98 return *this;
99 }
100
103};
104
111struct SC_FILE_SYSTEM_EXPORT FileSystem
112{
113 bool preciseErrorMessages = false;
114
117
121 Result init(StringSpan initialDirectory);
122
127
130
138
146
155 Result copyFile(StringSpan source, StringSpan destination, CopyFlags copyFlags = CopyFlags())
156 {
157 return copyFiles(CopyOperation{source, destination, copyFlags});
158 }
159
165
174 Result copyDirectory(StringSpan source, StringSpan destination, CopyFlags copyFlags = CopyFlags())
175 {
176 return copyDirectories(CopyOperation{source, destination, copyFlags});
177 }
178
188
193
198 Result removeFile(StringSpan source) { return removeFiles({source}); }
199
204
209
215
222 Result removeDirectoryRecursive(StringSpan directory) { return removeDirectoriesRecursive({directory}); }
223
229
234 Result removeEmptyDirectory(StringSpan directory) { return removeEmptyDirectories({directory}); }
235
241
246 Result makeDirectory(StringSpan directory) { return makeDirectories({directory}); }
247
252
256 Result makeDirectoryIfNotExists(StringSpan directory) { return makeDirectoriesIfNotExists({directory}); }
257
263
268 Result makeDirectoryRecursive(StringSpan directory) { return makeDirectoriesRecursive({directory}); }
269
274 Result createSymbolicLink(StringSpan sourceFileOrDirectory, StringSpan linkFile);
275
281
286 [[nodiscard]] bool exists(StringSpan fileOrDirectory);
287
291 [[nodiscard]] bool existsAndIsDirectory(StringSpan directory);
292
299 [[nodiscard]] bool existsAndIsFile(StringSpan file);
300
304 [[nodiscard]] bool existsAndIsLink(StringSpan file);
305
310 [[nodiscard]] bool canAccess(StringSpan fileOrDirectory, AccessMode accessMode = AccessMode::Exists);
311
316 [[nodiscard]] bool moveDirectory(StringSpan sourceDirectory, StringSpan destinationDirectory);
317
326 Result write(StringSpan file, Span<const uint8_t> data);
327
334
340
346 template <typename T>
347 Result read(StringSpan file, T& data)
348 {
349 return read(file, GrowableBuffer<T>{data});
350 }
351
356 Result read(StringSpan file, IGrowableBuffer&& buffer);
357
360
365 Result stat(StringSpan file, FileStat& fileStat);
366
371 Result lstat(StringSpan file, FileStat& fileStat);
372
378
384
390
397
404
410
416
419 struct SC_FILE_SYSTEM_EXPORT Operations
420 {
421 static Result access(StringSpan path, AccessMode accessMode);
422 static Result createSymbolicLink(StringSpan sourceFileOrDirectory, StringSpan linkFile);
423 static Result createHardLink(StringSpan sourceFile, StringSpan linkFile);
424 static Result makeDirectory(StringSpan dir);
425 static Result exists(StringSpan path);
426 static Result existsAndIsDirectory(StringSpan path);
427 static Result existsAndIsFile(StringSpan path);
428 static Result existsAndIsLink(StringSpan path);
429 static Result makeDirectoryRecursive(StringSpan path);
430 static Result removeEmptyDirectory(StringSpan path);
431 static Result moveDirectory(StringSpan source, StringSpan destination);
432 static Result removeFile(StringSpan path);
433 static Result copyFile(StringSpan srcPath, StringSpan destPath, FileSystemCopyFlags flags);
434 static Result rename(StringSpan path, StringSpan newPath);
435 static Result copyDirectory(StringSpan srcPath, StringSpan destPath, FileSystemCopyFlags flags);
436 static Result removeDirectoryRecursive(StringSpan directory);
437 static Result stat(StringSpan path, FileSystemStat& fileStat);
438 static Result lstat(StringSpan path, FileSystemStat& fileStat);
439 static Result getFileStat(StringSpan path, FileSystemStat& fileStat);
440 static Result readSymbolicLink(StringSpan path, StringPath& destination);
441 static Result chmod(StringSpan path, uint32_t mode);
442 static Result chown(StringSpan path, uint32_t uid, uint32_t gid);
443 static Result lchown(StringSpan path, uint32_t uid, uint32_t gid);
444 static Result lchmod(StringSpan path, uint32_t mode);
445 static Result setLastModifiedTime(StringSpan path, TimeMs time);
446
447 static StringSpan getExecutablePath(StringPath& executablePath);
448 static StringSpan getCurrentWorkingDirectory(StringPath& currentWorkingDirectory);
449 static StringSpan getApplicationRootDirectory(StringPath& applicationRootDirectory);
450
451 private:
452 struct Internal;
453 };
454
455 private:
456 [[nodiscard]] bool convert(const StringSpan file, StringPath& destination, StringSpan* encodedPath = nullptr);
457
458 StringPath fileFormatBuffer1;
459 StringPath fileFormatBuffer2;
460 StringPath currentDirectory;
461
462 char errorMessageBuffer[256] = {0};
463
464 Result formatError(int errorNumber, StringSpan item, bool isWindowsNativeError);
465 struct Internal;
466};
468} // namespace SC
FileSystemAccessMode
Access mode for path checks.
Definition FileSystem.h:67
FileSystemEntryType
A structure to describe file stats.
Definition FileSystem.h:25
@ 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:27
unsigned long long uint64_t
Platform independent (8) bytes unsigned int.
Definition PrimitiveTypes.h:33
unsigned int uint32_t
Platform independent (4) bytes unsigned int.
Definition PrimitiveTypes.h:29
A structure to describe copy flags.
Definition FileSystem.h:76
FileSystemCopyFlags & setUseCloneIfSupported(bool value)
If true copy will use native filesystem clone os api.
Definition FileSystem.h:95
FileSystemCopyFlags & setOverwrite(bool value)
If true copy will overwrite existing files in the destination.
Definition FileSystem.h:86
bool useCloneIfSupported
If true copy will use native filesystem clone os api.
Definition FileSystem.h:102
bool overwrite
If true copy will overwrite existing files in the destination.
Definition FileSystem.h:101
A structure to describe file stats.
Definition FileSystem.h:35
uint32_t mode
POSIX st_mode.
Definition FileSystem.h:46
uint32_t reparseTag
Windows reparse tag.
Definition FileSystem.h:59
size_t hardLinkCount
Number of hard links to the entry.
Definition FileSystem.h:39
TimeMs accessedTime
Time when file was last accessed when available.
Definition FileSystem.h:41
TimeMs creationTime
Time when file was created when available.
Definition FileSystem.h:40
uint64_t blockSize
POSIX st_blksize.
Definition FileSystem.h:53
FileSystemEntryType entryType
Type of entry stored at path.
Definition FileSystem.h:36
size_t fileSize
Size of the file in bytes.
Definition FileSystem.h:38
uint64_t blocks
POSIX st_blocks.
Definition FileSystem.h:52
uint32_t gid
POSIX st_gid.
Definition FileSystem.h:48
uint64_t inode
POSIX st_ino.
Definition FileSystem.h:49
uint64_t fileIndex
Windows file index.
Definition FileSystem.h:61
uint64_t specialDevice
POSIX st_rdev.
Definition FileSystem.h:51
uint32_t uid
POSIX st_uid.
Definition FileSystem.h:47
TimeMs modifiedTime
Time when file was last modified.
Definition FileSystem.h:42
uint32_t volumeSerialNumber
Windows volume serial number.
Definition FileSystem.h:60
uint64_t device
POSIX st_dev.
Definition FileSystem.h:50
uint32_t attributes
Windows file attributes.
Definition FileSystem.h:58
Specify source, destination and flags for a copy operation.
Definition FileSystem.h:133
StringSpan destination
Copy operation sink (can be a {relative | absolute} {file | directory} path)
Definition FileSystem.h:135
CopyFlags copyFlags
Copy operation flags (overwrite, use clone api etc.)
Definition FileSystem.h:136
StringSpan source
Copy operation source (can be a {relative | absolute} {file | directory} path)
Definition FileSystem.h:134
Low level filesystem API, requiring paths in native encoding (UTF-16 on Windows, UTF-8 elsewhere)
Definition FileSystem.h:420
Execute fs operations { exists, copy, delete } for { files and directories }.
Definition FileSystem.h:112
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:198
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:347
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:268
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:246
Result removeDirectoryRecursive(StringSpan directory)
Remove single directory with its entire content (like posix rm -rf)
Definition FileSystem.h:222
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:174
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:155
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:256
Result removeEmptyDirectory(StringSpan directory)
Removes an empty directory.
Definition FileSystem.h:234
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:50