// append.cpp -- appending information to a file #include <iostream> #include <fstream> #include <string> #include <cstdlib> // (or stdlib.h) for exit() const char * file = "1.txt"; // 我要打开的当前文件夹中的文本 int main() { using namespace std; char ch; // show initial contents ifstream fin; fin.open(file); if (fin.is_open()) { cout << "Here are the current contents of the " << file << " file:\n"; while (fin.get(ch)) cout << ch; fin.close(); } // 以追加的方式添加新的内容 ofstream fout(file, ios::out | ios::app); // 以写入,只追加的方式 if (!fout.is_open()) { cerr << "Can't 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 contents of the " << file << " file:\n"; while (fin.get(ch)) cout << ch; fin.close(); } cout << "Done.\n"; return 0; }
文件流fstream 函数
最新推荐文章于 2024-06-27 16:39:17 发布