Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<string>
- #include<fstream>
- #include<vector>
- const char FILE_NAME[] = "file.txt"; //kude se namira faila
- class Entity {
- std::string name;
- size_t id;
- std::string password;
- public:
- Entity() { name = ""; id = 0; password = ""; }
- Entity(const std::string& _name, size_t id, const std::string& _pass) { name = _name; this->id = id; password = _pass; }
- std::string getPass() const { return this->password; }
- std::string getName() const { return this->name; }
- void print() const { std::cout << this->name << " " << this->id << " " << this->password << '\n'; }
- size_t getID() const { return this->id; }
- ~Entity() { };
- };
- void saveEntityToFile(const char* location, const Entity& toSave) {
- std::ofstream outFile(location, std::ios::app);
- if (outFile.bad())
- return;
- //zapisvam: ime " " ID " " pass "\n"
- outFile << toSave.getName() << " " << toSave.getID() << " " << toSave.getPass() << '\n';
- outFile.close();
- }
- Entity readEntityFromFile(const char* info) {
- char nName[1024]; //pole za novo ime
- size_t ID = 0; //pole za ID
- char nPass[1024]; //pole za pass
- int ind = 0; //index na info
- int nInd = 0; //index na name
- int pInd = 0; //index na pass
- while (info[ind] != ' ') //dokato ne stigna " " (poneje taka razdelqm dannite vuv faila na zapisvaneto) kopiram
- nName[nInd++] = info[ind++];
- nName[nInd] = '\0';
- ind++; //skipvam praznoto prostranstvo na koeto sum vmomenta i produljavam da cheta
- while (info[ind] != ' ') {
- ID *= 10;
- ID += info[ind++] - '0';
- }
- ind++;
- while (info[ind] != '\0')//\0 zashtoto e posledniq element i nqma " " a '\0'
- nPass[pInd++] = info[ind++];
- nPass[pInd] = '\0';
- return Entity(nName, ID, nPass); //vrushtam kopie ot zapisanoto entity
- }
- int main() {
- Entity test("Entity1", 1234, "Password");
- saveEntityToFile(FILE_NAME, test);
- Entity test2("Entity2", 5679, "Password2");
- saveEntityToFile(FILE_NAME, test2);
- Entity test3("Entity3", 1357, "Password3");
- saveEntityToFile(FILE_NAME, test3);
- std::ifstream inFile(FILE_NAME); //otvarqm fail
- if (inFile.bad())
- return 0;
- std::vector<Entity> data; //vektor kudeto shte pazq dannite
- while (!inFile.eof()) {
- char buff[1024]; //char masiv v koito shte zapisvam redovete na faila(1 red = 1 entity)
- inFile.getline(buff, 1024);//getline vzema reda
- Entity readedEntity = readEntityFromFile(buff); //cheta
- if (strlen(buff) != 0)//poneje naktaq imam nov red koito pak go chete getlaina prosto kato ""
- data.push_back(readedEntity); //push
- }
- for (auto _val : data) //za vseki element vuv vektora izpulnqva koda po - dolu. dosta polezno e da se znae ako rabotish s std::vector
- _val.print();
- inFile.close();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement