From 6e57a86338e9408ef9e1bb3a2d38777f8da822c6 Mon Sep 17 00:00:00 2001 From: Shwoomple <> Date: Wed, 19 Oct 2022 10:43:23 +0530 Subject: [PATCH] lib/file: Implement write functions --- src/lib/file.cpp | 26 +++++++++++++++++++++++--- src/test/file.cpp | 20 ++++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/src/lib/file.cpp b/src/lib/file.cpp index 38f3e27..5c7863a 100644 --- a/src/lib/file.cpp +++ b/src/lib/file.cpp @@ -134,10 +134,7 @@ ErrorOrVoid File::writeByte(uint8_t byte){ bool failure = false; try{ - - this->fileStream.seekg(this->cursorPosition); this->fileStream << byte; - this->cursorPosition++; }catch(std::exception& e){ failure = true; } @@ -145,6 +142,29 @@ ErrorOrVoid File::writeByte(uint8_t byte){ return failure ? ErrorOrVoid(true, ErrorCodes::UNKNOWN) : ErrorOrVoid(); } +ErrorOrVoid File::write(std::vector data){ + bool failure = false; + + try{ + this->fileStream << std::string(data.begin(), data.end()); + }catch(std::exception& e){ + failure = true; + } + + return failure ? ErrorOrVoid(true, ErrorCodes::UNKNOWN) : ErrorOrVoid(); +} + +ErrorOrVoid File::writeString(tiny_utf8::string data){ + bool failure = false; + + try{ + this->fileStream << data; + }catch(std::exception& e){ + failure = true; + } + return failure ? ErrorOrVoid(true, ErrorCodes::UNKNOWN) : ErrorOrVoid(); +} + ErrorOr File::open(std::string path, char mode, uint64_t startPosition){ if (!std::filesystem::exists(path)) { return ErrorOr(true, ErrorCodes::FILE_NOT_FOUND, nullptr); diff --git a/src/test/file.cpp b/src/test/file.cpp index 6ec836b..ea49669 100644 --- a/src/test/file.cpp +++ b/src/test/file.cpp @@ -47,6 +47,7 @@ int main(){ File *writeFile; File *readFile; + //writeByte test writeFile = File::open("resources/unicode_data/writeTest", 'w').value; writeFile->writeByte('a'); writeFile->close(); @@ -55,4 +56,23 @@ int main(){ uint8_t testByte = readFile->readByte().value; ASSERT(testByte == 'a'); std::cout << "Passed write byte test." << std::endl; + + //write test + writeFile->open(); + writeFile->write(std::vector({'a', 'b', 'c'})); + writeFile->close(); + + readFile->cursorPosition = 0; + tiny_utf8::string testBytes = readFile->readString(3).value; + ASSERT(testBytes == "abc"); + std::cout << "Passed write test." << std::endl; + + writeFile->open(); + writeFile->writeString(tiny_utf8::string("Hallo")); + writeFile->close(); + + readFile->cursorPosition = 0; + tiny_utf8::string testString = readFile->readString(5).value; + ASSERT(testString == "Hallo"); + std::cout << "Passed write string test." << std::endl; }