1.设在当前路径下已经存在文件1.txt和2.txt。运行后, 屏幕上无输出,但当前路径下多了一个文件3.txt。分别打开三 个文件,可见文件1.txt和2.txt的内容合并到了文件3.txt中,并在末尾新增一行。
#include <iostream> #include <fstream> #include <cstring> #include <cstdlib> using namespace std; int main() { string filename1, filename2, newfilename; cout << "输入要合并的两个文件名: " ; cin >> filename1 >> filename2; cout << "输入合并后新文件名: " ; cin >> newfilename; ofstream fout; // 输出文件流对象 ifstream fin; // 输入文件流对象 fin.open(filename1); // 将输入文件流对象fin与文件filename1建立关联 if(!fin.is_open()) { // 如果打开文件失败,则输出错误提示信息并退出 cerr << "fail to open file " << filename1 << endl; exit(0); } fout.open(newfilename); // 将输出文件流对象fout与文件newfilename建立关联 if(!fin.is_open()) { // 如果创建/打开文件失败,输出错误提示信息并退出 cerr << "fail to open file " << newfilename << endl; exit(0); } char ch; // 从文件输入流对象fin中获取字符,并将其插入到文件输出流对象fout中 while(fin.get(ch)) fout << ch; fin.close(); // 关闭文件输入流对象fin与文件filename1的关联 fout << endl; // 向文件输出流对象fout中插入换行 fin.open(filename2); // 将输入文件流对象fin与文件filename2建立关联 if(!fin.is_open()) { // 如果打开文件失败,则输出错误提示信息并退出 cerr << "fail to open file " << filename2 << endl; exit(0); } // 从文件输入流对象fin中获取字符,并将其插入到文件输出流对象fout中 while(fin.get(ch)) fout << ch; fin.close(); // 关闭文件输入流对象fin与文件filename2的关联 fout.close(); // 关闭文件输出流对象fout与文件newfilename的关联 ofstream fapp; fapp.open(newfilename,ios_base::app); if(!fapp.is_open()) { cerr << "fail to open file " << filename2 << endl; exit(0); } fapp<<endl; fapp<<"merge successfully."; return 0; }
2.已知名单列表文件list.txt。编写一个应用程序,实现从名单中随机抽点n位同学(n由键盘输入),在屏幕上显 示结果,同时也将结果写入文本文件,文件名自动读取当天系统日期,如20190611.txt。
#include <iostream> #include <fstream> #include <cstdlib> #include <ctime> #include <string> #include "utils.h" using namespace std; int main() { ofstream fout; ifstream fin; string a[100][100]; string textname,filename,line0; int n,num,i,j; textname = getCurrentDate()+".txt";//加“.txt”直接生成文档,不加则是文件形式,可以选择打开方式查看。 cout << "输入名单名: " ; cin >> filename; cout << "随机抽点人数:"; cin>>n; cout<<"随机抽点中..." <<endl; fout.open(textname); if(!fout.is_open()) { cerr << "fail to open file " << textname << endl; exit(0); } fin.open(filename); if(!fin.is_open()) { cerr << "fail to open file " << filename << endl; exit(0); } else{ for(i=0;i<=82;i++) { getline(fin,line0); a[i][100]=line0; } srand(time(NULL)); for(j=0;j<=n-1;j++) { num = (rand() % 83); cout<<a[num][100]<<endl; fout<<a[num][100]<<endl; } } fin.close(); fout.close(); return 0; }
3.编程统计英文文本文件中字符数(包括空格)、单词数、行数。文件名由键盘输入。
#include <iostream> #include <fstream> #include <cstring> #include <cstdlib> using namespace std; int main(){ string textname,line0; char a[1000]; cout<<"输入要统计的英文文本文件名:"; cin>>textname; ifstream fin; int n=0,ln=1,wn=1; char c; fin.open(textname); if(!fin.is_open()) { cerr << "fail to open file " << textname << endl; exit(0); } while(fin.get(c)) { if(c!=‘\n‘) { n++; if(c==‘ ‘) wn++; } else { wn++; ln++; } } cout<<"字符数: "<<n<<endl; cout<<"单词数:"<<wn<<endl; cout<<"行数:"<<ln<<endl; return 0; }
小结
原文:https://www.cnblogs.com/Ann-88/p/11029052.html