parsing user files, showing them with threads

cool, maybe we'll use it?
 avatar
chamanEiqbal
c_cpp
a year ago
2.7 kB
6
Indexable
#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
#include <fstream>
#include <thread>
#include <filesystem>
#include <unordered_set>
#include <vector>
#include <mutex>

using namespace std;
namespace fs = std::filesystem;

enum lengths {
    USER_LENGTH = 5,
    PASSWORD_LENGTH = 9,
    FRIENDS_LENGTH = 8,
    POST_LENGTH = 5 
};

mutex usersMutex;
struct User {
	std::string userID;
	std::string password;
	std::unordered_set < std::string > friends;
    std::unordered_set < std::string > posts;
};

vector<User> users;

void parseUser(string filename) {
    
    stringstream ss;
    fstream file(filename, ios::in);
    if(file.is_open()) {
        cout << "file has opened." << endl;
        ss << file.rdbuf();
        file.close(); 
    }

    string buf = ss.str();

    size_t pos = buf.find("User:");
    if(pos != string::npos) {
        buf.erase(pos, USER_LENGTH);
    }

    pos = buf.find("Password:");
    if(pos != string::npos) {
        buf.erase(pos, PASSWORD_LENGTH);
    }

    pos = buf.find("Friends");
    if(pos != string::npos) {
        buf.erase(pos, FRIENDS_LENGTH);
    }

     while(buf.find("Post: ") != string::npos) {
        pos = buf.find("Post: ");
        buf.erase(pos, POST_LENGTH);
    }

    istringstream iss(buf);
   User user; 
    getline(iss, user.userID);

    getline(iss, user.password);

    string friendsline;
    getline(iss, friendsline);

    istringstream friendstringstream(friendsline);
    string friendName;
    while(friendstringstream >> friendName) {
        user.friends.insert(friendName);
    }

    string postLine;
    while(getline(iss, postLine)) {
        user.posts.insert(postLine);
    }

    lock_guard<mutex> lock(usersMutex);
    users.push_back(user);
}

void showUsers() {
    lock_guard<mutex> lock(usersMutex);
    for(auto &elem : users) {
        cout << "Username: " + elem.userID << endl;
        cout << "Password: " + elem.password << endl; 
    }
}



int main() {

    vector<thread*> threads;
    for(auto &entry : fs::directory_iterator(fs::current_path().string()+"/users")) {
        if(entry.is_regular_file() && entry.path().extension() == ".txt") {
            thread *t1 = new thread(parseUser, entry.path().string());
            threads.push_back(t1);
        }
    }

    for(auto &elem : threads) {
        elem->join();
    }

    
    thread *t2 = new thread(showUsers);
    t2->join();

    for(int i = 0; i < 10; i++) {
        cout << i << endl;
    }

    
    system("pause");
    return 0;
}
Editor is loading...