lib/file: Implement write functions

Soda
Shwoomple 2022-10-19 10:43:23 +05:30
parent c54eb48887
commit 6e57a86338
2 changed files with 43 additions and 3 deletions

View File

@ -134,10 +134,7 @@ ErrorOrVoid File::writeByte(uint8_t byte){
bool failure = false; bool failure = false;
try{ try{
this->fileStream.seekg(this->cursorPosition);
this->fileStream << byte; this->fileStream << byte;
this->cursorPosition++;
}catch(std::exception& e){ }catch(std::exception& e){
failure = true; failure = true;
} }
@ -145,6 +142,29 @@ ErrorOrVoid File::writeByte(uint8_t byte){
return failure ? ErrorOrVoid(true, ErrorCodes::UNKNOWN) : ErrorOrVoid(); return failure ? ErrorOrVoid(true, ErrorCodes::UNKNOWN) : ErrorOrVoid();
} }
ErrorOrVoid File::write(std::vector<uint8_t> 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*> File::open(std::string path, char mode, uint64_t startPosition){ ErrorOr<File*> File::open(std::string path, char mode, uint64_t startPosition){
if (!std::filesystem::exists(path)) { if (!std::filesystem::exists(path)) {
return ErrorOr<File*>(true, ErrorCodes::FILE_NOT_FOUND, nullptr); return ErrorOr<File*>(true, ErrorCodes::FILE_NOT_FOUND, nullptr);

View File

@ -47,6 +47,7 @@ int main(){
File *writeFile; File *writeFile;
File *readFile; File *readFile;
//writeByte test
writeFile = File::open("resources/unicode_data/writeTest", 'w').value; writeFile = File::open("resources/unicode_data/writeTest", 'w').value;
writeFile->writeByte('a'); writeFile->writeByte('a');
writeFile->close(); writeFile->close();
@ -55,4 +56,23 @@ int main(){
uint8_t testByte = readFile->readByte().value; uint8_t testByte = readFile->readByte().value;
ASSERT(testByte == 'a'); ASSERT(testByte == 'a');
std::cout << "Passed write byte test." << std::endl; std::cout << "Passed write byte test." << std::endl;
//write test
writeFile->open();
writeFile->write(std::vector<uint8_t>({'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;
} }