Browse Source

Add system::readFile/writeFile().

tags/v2.0.0
Andrew Belt 3 years ago
parent
commit
a2c5a7695f
2 changed files with 49 additions and 0 deletions
  1. +17
    -0
      include/system.hpp
  2. +32
    -0
      src/system.cpp

+ 17
- 0
include/system.hpp View File

@@ -111,18 +111,35 @@ Examples:
*/
std::string getExtension(const std::string& path);

// File read/write

/** Reads an entire file into a memory buffer.
Throws on error.
*/
std::vector<uint8_t> readFile(const std::string& path);

/** Writes a memory buffer to a file, overwriting if already exists.
Throws on error.
*/
void writeFile(const std::string& path, const std::vector<uint8_t>& data);

/** Compresses the contents of a directory (recursively) to an archive.
Uses the Unix Standard TAR + Zstandard format (.tar.zst).
An equivalent shell command is

ZSTD_CLEVEL=1 tar -cf archivePath --zstd -C dirPath .

Throws on error.
*/
void archiveDirectory(const std::string& archivePath, const std::string& dirPath, int compressionLevel = 1);
std::vector<uint8_t> archiveDirectory(const std::string& dirPath, int compressionLevel = 1);

/** Extracts an archive into a directory.
An equivalent shell command is

tar -xf archivePath --zstd -C dirPath

Throws on error.
*/
void unarchiveToDirectory(const std::string& archivePath, const std::string& dirPath);
void unarchiveToDirectory(const std::vector<uint8_t>& archiveData, const std::string& dirPath);


+ 32
- 0
src/system.cpp View File

@@ -272,6 +272,38 @@ std::string getExtension(const std::string& path) {
}


std::vector<uint8_t> readFile(const std::string& path) {
std::vector<uint8_t> data;
FILE* f = std::fopen(path.c_str(), "rb");
if (!f)
throw Exception("Cannot read file %s", path.c_str());
DEFER({
std::fclose(f);
});

// Get file size so we can make a single allocation
std::fseek(f, 0, SEEK_END);
size_t len = std::ftell(f);
std::fseek(f, 0, SEEK_SET);

data.resize(len);
std::fread(data.data(), 1, len, f);
return data;
}


void writeFile(const std::string& path, const std::vector<uint8_t>& data) {
FILE* f = std::fopen(path.c_str(), "wb");
if (!f)
throw Exception("Cannot create file %s", path.c_str());
DEFER({
std::fclose(f);
});

std::fwrite(data.data(), 1, data.size(), f);
}


/** Returns `p` in relative path form, relative to `base`
Limitation: `p` must be a descendant of `base`. Doesn't support adding `../` to the return path.
*/


Loading…
Cancel
Save