Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //It's database library
- //Use the function "set_filesize" to set a default size of the data file
- //Use the function "set_path" to set path for saving data files
- #ifndef DATABASE_LIBRARY_H
- #define DATABASE_LIBRARY_H
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <cassert>
- #include <cstring>
- using namespace std;
- string filename = "data0";
- string path;
- int num = 0;
- int default_filesize = 8388608;
- void set_path(const string &saving_path) {
- path = saving_path;
- }
- void set_filesize(int custom_size) {
- default_filesize = custom_size;
- }
- bool is_datafile_full(const string ¤t_filename) {
- ifstream file(current_filename.c_str(), ifstream::in | ifstream::binary);
- int current_filesize = file.tellg();
- file.close();
- if (default_filesize <= current_filesize) {
- return true;
- }
- return false;
- }
- void store(int id, void* data) {
- if (path.empty()) {
- throw std::runtime_error("path is invalid");
- }
- if (is_datafile_full(filename)) {
- num++;
- string num_str = to_string(num);
- filename = "data" + num_str;
- }
- ofstream datafile;
- datafile.open(path + filename + ".txt");
- datafile << id << " " << data << endl;
- datafile.close();
- }
- string load(int id) {
- string line;
- ifstream datafile;
- datafile.open(path + filename + ".txt");
- while (getline(datafile, line)) {
- size_t pos = line.find(' ');
- string user_id = line.substr(0, line.find(' '));
- if (user_id == to_string(id)) {
- datafile.close();
- string user_data = line.substr(pos + 1);
- return user_data;
- }
- }
- }
Add Comment
Please, Sign In to add comment