lib/file: Implement cut function.

windows
Shwoomple 2022-11-12 10:59:08 +05:30
parent 76dd30c45a
commit 9bda607649
2 changed files with 40 additions and 0 deletions

View File

@ -263,6 +263,32 @@ ErrorOr<uint8_t> File::cutByte(){
return failure ? ErrorOr<uint8_t>(true, ErrorCodes::UNKNOWN) : ErrorOr<uint8_t>(byte);
}
ErrorOr<std::vector<uint8_t>> File::cut(uint64_t length){
bool failure = false;
std::vector<uint8_t> bytes;
try{
uint8_t* buffer = new uint8_t[this->size.value];
std::vector<uint8_t> readData;
this->fileStream.read(reinterpret_cast<char*>(buffer), this->size.value);
readData = std::vector<uint8_t>(buffer, buffer+this->size.value);
bytes = std::vector<uint8_t>(readData.begin() + this->cursorPosition, readData.begin() + (this->cursorPosition + length));
readData.erase(readData.begin() + this->cursorPosition, readData.begin() + (this->cursorPosition + length));
std::filesystem::resize_file(this->path, readData.size());
this->fileStream.seekg(0);
this->write(readData);
this->cursorPosition += length;
delete[] buffer;
}catch(std::exception& e){
failure = true;
}
return failure ? ErrorOr<std::vector<uint8_t>>(true, ErrorCodes::UNKNOWN) :ErrorOr<std::vector<uint8_t>>(bytes);
}
ErrorOr<File*> File::open(std::string path, char mode, uint64_t startPosition){
if (!std::filesystem::exists(path) && (mode == 'r' || mode == 'm')) {
return ErrorOr<File*>(true, ErrorCodes::FILE_NOT_FOUND, nullptr);

View File

@ -180,4 +180,18 @@ int main(){
ASSERT(cutByte.value == '.');
ASSERT(cutByteString == "Hallo, Hi THE CAKE IS A LIE, Ich bin Shwoomple");
std::cout << "Passed cut byte test." << std::endl;
modifyFile->open();
modifyFile->cursorPosition = 9;
ErrorOr<std::vector<uint8_t>> cutBytes = modifyFile->cut(18);
modifyFile->close();
readFile->open();
readFile->cursorPosition = 0;
tiny_utf8::string cutBytesString = readFile->readString(readFile->size.value).value;
readFile->close();
ASSERT(cutBytes.value == std::vector<uint8_t>({' ', 'T', 'H', 'E', ' ', 'C', 'A', 'K', 'E', ' ', 'I', 'S', ' ','A', ' ', 'L', 'I', 'E'}))
ASSERT(cutBytesString == "Hallo, Hi, Ich bin Shwoomple");
std::cout << "Passed cut test." << std::endl;
}