1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
|
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
#include <sstream>
struct Person
{
std::string first, last;
unsigned int age;
bool isMale;
};
bool searchPerson(std::string fileName, std::string fullName)
{
std::string str;
std::ifstream fin(fileName.c_str());
while (getline(fin, str))
if (str == fullName)
{
fin.close();
return true;
}
fin.close();
return false;
}
void savePerson(std::string fileName, Person p)
{
std::string fullName;
fullName = p.last + ", " + p.first;
if (searchPerson(fileName, fullName)) //person exists in file
{
std::string str;
std::string tempFileName = "temp_" + fileName;
std::ifstream fin(fileName.c_str()); //read from old file
std::ofstream fout(tempFileName.c_str()); //create temp file
while (getline(fin, str))
{
if (str != fullName) //don't change anything that's not our Person
fout << str << std::endl;
else
{
fout << fullName << std::endl;
fout << p.age << std::endl;
if (p.isMale)
fout << "Male" << std::endl;
else
fout << "Female" << std::endl;
fout << std::endl;
//ignore the next 3 lines
getline(fin, str);
getline(fin, str);
getline(fin, str);
}
}
fin.close();
fout.close();
remove(fileName.c_str()); //delete old file
rename(tempFileName.c_str(), fileName.c_str()); //rename temp file
}
else //person doesn't exist in file
{
//add to the file
std::ofstream fout(fileName.c_str(), std::ofstream::out | std::ofstream::app);
fout << fullName << std::endl;
fout << p.age << std::endl;
if (p.isMale)
fout << "Male" << std::endl;
else
fout << "Female" << std::endl;
fout << std::endl;
fout.close();
}
};
bool loadPerson(std::string fileName, std::string fullName, Person &p)
{
if (!searchPerson(fileName, fullName)) //person doesn't exist in file!
return false;
std::string str;
std::ifstream fin(fileName.c_str());
while (getline(fin, str))
{
if (str == fullName)
{
p.last = str.substr(0, str.find(','));
p.first = str.substr(str.find(',') + 2);
getline(fin, str);
std::istringstream sin(str);
sin >> p.age;
getline(fin, str);
p.isMale = (str == "Male");
fin.close();
return true;
}
}
fin.close();
return false; //it should never get to here
}
|