#include<iostream>
#include<fstream>// fout
#include<vector>
#include<string>
#include<algorithm>// for_each()
using namespace std;
// write to file. use ifstream to input to stream,in which use ofstream to output from
class Store
{
private:
ofstream& fout;// member
public:
Store(ofstream& f) :fout(f) {}; // constructor
void operator()(string & str);
~Store() {};
};
// member functions of class Store
void Store::operator()(string & str)
{
size_t len = str.length();// count of characters in string
fout.write((char*)& len, sizeof(size_t));// write len to file
// wanna extract characters from string,but string obj don't store characters by itselt
// but store a pointer points to heap block, so need to store characters to an array,then
// use write() to get data from the address of this array which stores characters
fout.write(str.data(), len);// take len characters from array pointed by str.data(),or use (char*)str.c_str()
fout << '\n';// seperate each log,more obvious for human
}
// show string obj
void ShowStr(string& str)
{
cout << str << '\n';
}
void GetStrs(istream& fin, vector<string>& vs)
{
//fin.read(),don't use this way, can't directly cover,
// string itself don't contains characters, but a pointer points heap block
while (!fin.eof())
{
// acquir string length
string strtmp;
size_t len = 0;
fin.read((char*)& len, sizeof(size_t));// read sizeof(int) binary data to address of len
// acquir characters
char ch;
for (size_t i = 0; i < len; i++)
{
fin.read((char*)&ch, sizeof(char));// or fin.get(ch);
strtmp.push_back(ch);
}
vs.push_back(strtmp);
fin.get();// dicard '\n' written by read()
}
}
int main()
{
vector<string> vostr;
string temp;
// acquire strings
cout << "Enter strings (empty line to quit):\n";
while (getline(cin, temp) && temp[0] != '\0')// input newline to stop looping
vostr.push_back(temp);
cout << "Here is your input.\n";
for_each(vostr.begin(), vostr.end(), ShowStr);
// store in a file
ofstream fout("strings.dat", ios_base::out | ios_base::binary);
for_each(vostr.begin(), vostr.end(), Store(fout));
fout.close();
// recover file contents
vector<string> vistr;
ifstream fin("strings.dat", ios_base::in | ios_base::binary);
if (!fin.is_open())
{
cerr << "Could not open file for input.\n";
exit(EXIT_FAILURE);
}
GetStrs(fin, vistr);
cout << "\nHere are the strings read from the file:\n";
for_each(vistr.begin(), vistr.end(), ShowStr);
cin.get();
return 0;
}
C++ Premier Plus 6th edition - Programming excercise - Chapter17 - 7
最新推荐文章于 2019-10-22 15:51:40 发布