Implementation of the UserManager entity in the Separate Storage example

user_manager.cpp

#include "user_manager.h"

#include <iostream>

#include <fstream>

#include <string>

bool UserManager::Read(const std::string& userListFileName)

{

std::ifstream userListFile;

userListFile.open(userListFileName);

if (!userListFile.is_open())

{

return false;

}

for (std::string userName; userListFile >> userName;)

{

m_userList.push_back(userName);

}

userListFile.close();

return m_userList.size() > 0;

}

user_manager.h

/* © 2021 AO Kaspersky Lab */

#ifndef SEPARATE_STORAGE_USER_MANAGER_H

#define SEPARATE_STORAGE_USER_MANAGER_H

#include <list>

#include <string>

typedef std::list<std::string> UserList;

class UserManager

{

public:

// @brief Reads a string from the user list file and stores it in m_userList.

// This function is used only to demonstrate the capability to read from a file

// and does not carry another payload.

// @param[in] path specification of the file we want to read

// @return true if successful, otherwise false

bool Read(const std::string& path);

// @brief Gets the contents of the m_userList variable.

// @return constant reference to m_userList

const UserList &Get()

{

return m_userList;

}

private:

UserList m_userList;

};

#endif

main.cpp

#include "user_manager.h"

#include "file_names.h"

#include <iostream>

#include <fstream>

#include <time.h>

const std::string Tag = "[UserManager] ";

const std::string ErrorTag = "[Error] ";

void UserListOutput(const UserList& users)

{

for(const auto& User : users)

{

std::cout << Tag << "User name: " << User << std::endl;

}

}

void OpenUnavailableFile(const std::string &fileName)

{

std::cout << Tag << "Try to read unavailable file '" << fileName << "'" << std::endl;

std::ifstream inpFile;

inpFile.open(fileName);

if (!inpFile.is_open())

{

std::cout << Tag << "Unable to open the '" << fileName << "' file. It is correct behaviour." << std::endl;

}

else

{

std::cout << Tag << ErrorTag << “The ‘“ << fileName << “‘ file is open. It is not correct behaviour." << std::endl;

}

}

int main(int argc, char* argv[])

{

try

{

UserManager users;

// Reads a file that we can access.

std::cout << Tag << "Try to read '" << UserListFileName << "' file" << std::endl;

if (!users.Read(UserListFileName))

{

std::cout << Tag << ErrorTag << "Unable to read file: '" << UserListFileName << "'" << std::endl;

}

else

{

std::cout << Tag << "Success" << std::endl;

UserListOutput(users.Get());

}

// Attempts to read a file that we cannot access.

OpenUnavailableFile(CertificateFileName);

}

catch(std::exception& ex)

{

std::cout << Tag << ErrorTag << ex.what() << std::endl;

return EXIT_FAILURE;

}

return EXIT_SUCCESS;

}

Page top