实验六 流类库与I/O
一、实验内容
1、 合并两个文件到新文件中。文件名均从键盘输入
2、使用文件I/O流,以文本方式打开Part1中合并后的文件,在文件最后一行添加字符"merge successfully. "
#include <iostream> #include <fstream> #include <cstdlib> #include <string> using namespace std; int main() { ofstream fout; string filename; cout << "输入要添加的文件名: " ; cin >> filename; fout.open(filename,ios_base::app); if(!fout.is_open()) { cerr << "fail to open file " << filename << endl; system("pause"); exit(0); } fout << endl; fout<<"merge successfully."<<endl; fout.close(); return 0; }
效果如下:
3、已知名单列表文件list.txt。编写一个应用程序,实现从名单中随机抽点n位同学(n由键盘输入),在屏幕上显 示结果,同时也将结果写入文本文件,文件名自动读取当天系统日期,如20190611.txt。
#include <iostream> #include <fstream> #include <string> #include <cstdlib> #include <ctime> #include "utils.h" using namespace std; int main(){ string filename, newfilename,str; ifstream fin; ofstream fout; int n; cout << "输入名单列表文件名: " ; cin >> filename; cout << "输入随机抽点人数: " ; cin>>n; newfilename=getCurrentDate()+".txt"; fin.open(filename); if(!fin.is_open()) { cerr << "fail to open file " << filename << endl; system("pause"); exit(0); } fout.open(newfilename); if(!fout.is_open()) { cerr << "fail to open file " << newfilename << endl; system("pause"); exit(0); } srand(time(0)); while(n--){ int m=rand()%83+1,i=0; fin.seekg(0); while(getline(fin,str)&&i<m-1){ i++; } cout<<str<<endl; fout<<str<<endl; } fin.close(); fout.close(); return 0; }