Advertisement
Stoycho_KK

файлове

May 11th, 2021
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. #include<iostream>
  2. #include<string>
  3. #include<fstream>
  4.  
  5. const char FILE_NAME[] = "file.txt";
  6.  
  7. class Entity {
  8.     std::string name;
  9.     size_t id;
  10.     std::string password;
  11. public:
  12.     Entity() { name = ""; id = 0; password = ""; }
  13.     Entity(const std::string& _name, size_t id, const std::string& _pass) { name = _name; this->id = id; password = _pass; }
  14.  
  15.     std::string getPass() const { return this->password; }
  16.  
  17.     std::string getName() const { return this->name; }
  18.  
  19.     size_t getID() const { return this->id; }
  20.  
  21.     ~Entity() { };
  22. };
  23.  
  24. void saveEntityToFile(const char* location, const Entity& toSave) {
  25.     std::ofstream outFile(location, std::ios::app);
  26.    
  27.     if (outFile.bad())
  28.         return;
  29.  
  30.     outFile << toSave.getName() << " " << toSave.getID() << " " << toSave.getPass() << '\n';
  31.  
  32.     outFile.close();
  33. }
  34.  
  35. Entity readEntityFromFile(const char* location) {
  36.     std::ifstream inFile(location);
  37.     if (inFile.bad())
  38.         return Entity();
  39.  
  40.     std::string nName;
  41.     std::string nPass;
  42.     size_t ID;
  43.  
  44.     inFile >> nName >> ID >> nPass;
  45.  
  46.     inFile.close();
  47.  
  48.     return Entity(nName, ID, nPass);
  49. }
  50.  
  51. int main() {
  52.     Entity test("Entity1", 1234, "Password");
  53.     saveEntityToFile(FILE_NAME, test);
  54.     Entity readedEntity = readEntityFromFile(FILE_NAME);
  55.     std::cout << readedEntity.getName() << " " << readedEntity.getID() << " " << readedEntity.getPass() << '\n';
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement