//尚未调试通过
//向文件尾添加内容
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
char fileName[80];
char buffer[255];
char ch;
cout << "Please re-enter the file name:";
cin >> fileName;
ifstream fin;
fin.open(fileName);
if(fin)
{
cout << "Current file contents:\n";
while(fin.get(ch))
cout << ch;
cout << "\n****End of file contents***\n";
}
fin.close();
cout << "\nOpening " << fileName << " in append mode...\n";
ofstream fout;
fout.open(fileName,ios::app);
if(!fout)
{
cout << "Unable to open " << fileName << " for appending.\n";
return (1);
}
cout << "\nEnter text for the file: ";
cin.ignore(1,'\n');
cin.getline(buffer,255);
fout << buffer << "\n";
fout.close();
// { //本来不应当加这个大括号的,可是不加不能正常运行,没办法,原因不明。
// int TempIndex=0;
// while (fout && TempIndex<=10)
// {
// fout.close();
// TempIndex++;
// }
// if (TempIndex>=10)
// {
// cout << "Unable to close " << fileName << " after appended!";
// return (1);
// }
//
// }
fin.open(fileName);
// { //本来不应当加这个大括号的,可是不加不能正常运行,没办法,原因不明。
// int TempIndex=0;
// const int MaxLoop=100;
// while (!fin && TempIndex<=MaxLoop)
// {
// fin.open(fileName);
// TempIndex++;
// }
// cout << TempIndex;
// if (TempIndex>=MaxLoop)
// {
// cout << "Unable to open " << fileName << " for reading.\n";
// return (1);
// }
//
// }
if(!fin)
{
cout << "Unable to open " << fileName << " for reading.\n";
return (1);
}
cout << "\nHere's the contents of the file:\n";
while(fin.get(ch))
cout << ch;
cout << "\n***End of file contents***\n";
fin.close();
return 0;
}