TwITe

Untitled

Sep 25th, 2017
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. //It's database library
  2. //Use the function "set_filesize" to set a default size of the data file
  3. //Use the function "set_path" to set path for saving data files
  4. #ifndef DATABASE_LIBRARY_H
  5. #define DATABASE_LIBRARY_H
  6. #include <iostream>
  7. #include <fstream>
  8. #include <string>
  9. #include <cassert>
  10. #include <cstring>
  11. using namespace std;
  12. string filename = "data0";
  13. string path;
  14. int num = 0;
  15. int default_filesize = 8388608;
  16.  
  17. void set_path(const string &saving_path) {
  18.     path = saving_path;
  19. }
  20.  
  21. void set_filesize(int custom_size) {
  22.     default_filesize = custom_size;
  23. }
  24.  
  25. bool is_datafile_full(const string &current_filename) {
  26.     ifstream file(current_filename.c_str(), ifstream::in | ifstream::binary);
  27.     int current_filesize = file.tellg();
  28.     file.close();
  29.     if (default_filesize <= current_filesize) {
  30.         return true;
  31.     }
  32.     return false;
  33. }
  34.  
  35. void store(int id, void* data) {
  36.     if (path.empty()) {
  37.         throw std::runtime_error("path is invalid");
  38.     }
  39.     if (is_datafile_full(filename)) {
  40.         num++;
  41.         string num_str = to_string(num);
  42.         filename = "data" + num_str;
  43.     }
  44.     ofstream datafile;
  45.     datafile.open(path + filename + ".txt");
  46.     datafile << id << " " << data << endl;
  47.     datafile.close();
  48. }
  49.  
  50. string load(int id) {
  51.     string line;
  52.     ifstream datafile;
  53.     datafile.open(path + filename + ".txt");
  54.     while (getline(datafile, line)) {
  55.         size_t pos = line.find(' ');
  56.         string user_id = line.substr(0, line.find(' '));
  57.         if (user_id == to_string(id)) {
  58.             datafile.close();
  59.             string user_data = line.substr(pos + 1);
  60.             return user_data;
  61.         }
  62.     }
  63. }
Add Comment
Please, Sign In to add comment