FileManager.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include "../include/FileManager.h"
  2. FileManager::FileManager() {}
  3. FileManager::~FileManager() {
  4. cancelPut();
  5. closeGetFile();
  6. }
  7. bool FileManager::isUploading() { return this->putFile.is_open(); }
  8. bool FileManager::isDownloading() { return this->getFile.is_open(); }
  9. bool FileManager::openPutFile(const std::string &filename) {
  10. this->putBaseFileName = filename;
  11. this->putFileName = this->fileDirectory;
  12. this->putFileName.append(filename);
  13. // open file and test if it already exists
  14. this->putFile.open(this->putFileName, std::ios::app | std::ios::binary);
  15. if (this->putFile.tellp() != std::ios::beg) {
  16. // file already exists
  17. closePutFile();
  18. return false;
  19. } else {
  20. return true;
  21. }
  22. }
  23. bool FileManager::openGetFile(const std::string &filename, int &chunks) {
  24. this->getBaseFileName = filename;
  25. std::string file = this->fileDirectory;
  26. file.append(filename);
  27. this->getFile.open(file, std::ios::ate | std::ios::binary);
  28. if (this->getFile.is_open() == 0) {
  29. // file does not exist or cannot be opened
  30. return false;
  31. } else {
  32. size_t size = this->getFile.tellg();
  33. chunks = size / max_data_length + (size % max_data_length == 0 ? 0 : 1);
  34. this->getFile.seekg(std::ios::beg);
  35. return true;
  36. }
  37. }
  38. void FileManager::closePutFile() { this->putFile.close(); }
  39. void FileManager::closeGetFile() { this->getFile.close(); }
  40. void FileManager::cancelPut() {
  41. if (isUploading()) {
  42. closePutFile();
  43. std::remove(this->putFileName.c_str());
  44. }
  45. }
  46. bool FileManager::checkFilename(const std::string &name) {
  47. return name.find('/') == std::string::npos;
  48. }
  49. std::string FileManager::getGetBaseFileName() { return this->getBaseFileName; }
  50. std::string FileManager::getPutBaseFileName() { return this->putBaseFileName; }
  51. void FileManager::writePut(const std::vector<char> &data) {
  52. std::ostreambuf_iterator<char> output_iterator(this->putFile);
  53. std::copy(data.begin(), data.end(), output_iterator);
  54. }
  55. std::vector<char> FileManager::readGet() {
  56. char fileBuffer[max_data_length];
  57. int read = this->getFile.readsome(fileBuffer, max_data_length);
  58. std::vector<char> data;
  59. data.assign(fileBuffer, fileBuffer + read);
  60. return data;
  61. }