- #include<iostream>
- #include<fstream>
- #include<string>
- using namespace std;
- int win(string);
- int output(int, string);
- int input(int, string);
- int main()
- {
- string filename;
- cout << "请输入文件路径:";
- cin >> filename;
- win(filename);
- return 0;
- }
- int win(string filename)
- {
- int n,i,o;
- cin.clear();
- cout << "\\n1.文件输出" << endl;
- cout << "2.文件输入" << endl;
- cout << "3.退出" << endl;
- cout << "请选择操作:";
- cin >> n;
- switch(n)
- {
- case 1:
- {
- cout << "\\n1.输出每一行" << endl;
- cout << "2.输出每个单词" << endl;
- cout << "请选择文件输出操作:";
- cin >> o;
- output(o,filename);
- break;
- }
- case 2:
- {
- cout << "\\n1.清空并输入" << endl;
- cout << "2.附加输入" << endl;
- cout << "请选择文件输入操作:";
- cin >> i;
- input(i,filename);
- break;
- }
- case 3:
- cout << "\\n谢谢使用!" << endl;
- break;
- }
- }
- int output(int o, string filename)
- {
- ifstream out;
- out.clear();
- out.open(filename.c_str());
- string ostr;
- cout << filename << "文件内容为:" << endl;
- switch(o)
- {
- case 1:
- {
- while(getline(out,ostr))
- cout << ostr << endl;
- out.close();
- return win(filename);
- }
- case 2:
- {
- while(out >> ostr)
- cout << ostr << endl;
- out.close();
- return win(filename);
- }
- }
- }
- int input(int i, string filename)
- {
- ofstream in;
- string istr;
- cout << "\\n请输入文件内容(Ctrl+Z to end):" << endl;
- switch(i)
- {
- case 1:
- {
- in.clear();
- in.open(filename.c_str(), fstream::out|fstream::trunc);
- while(getline(cin,istr))
- in << istr;
- cout << "文件成功写入" << endl;
- in.close();
- return win(filename);
- }
- case 2:
- {
- in.clear();
- in.open(filename.c_str(), fstream::out|fstream::app);
- while(getline(cin,istr))
- in << istr;
- cout << "文件写入成功" << endl;
- in.close();
- return win(filename);
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/040320148866.html
来源: http://www.codesnippet.cn/detail/040320148866.html