来看看如何在文件末尾追加数据。
// append.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>//for exit()
const char* file = "guest.txt";
int main()
{
//std::cout << "Hello World!\n";
using namespace std;
char ch;
//show initial content
ifstream fin;
fin.open(file);
if (fin.is_open())
{
cout << "Here are the content of the "<<file<<"file:\n";
while (fin.get(ch))
{
cout << ch;
}
fin.close();
}
//add new names
ofstream fout(file,ios::out|ios::app);
if (!fout.is_open())
{
cerr << "Can not open" << file << "file for output.\n";
exit(EXIT_FAILURE);
}
cout << "Enter guest names (enter a blank line to quit):\n";
string name;
while (getline(cin,name)&&name.size()>0)
{
fout << name << endl;
}
fout.close();
//show revised file
fin.clear();//not necessary for some compilers
fin.open(file);
if (fin.is_open())
{
cout << "Here are the new content of the " << file << "file:\n";
while (fin.get(ch))
{
cout << ch;
}
fin.close();
}
cout << "Done.\n";
return 0;
}