实验8 流类库
实验内容
(1)编写程序,显示一个文本文件的内容。
#include <iostream>
#include<cstdio>
#include<fstream>
using namespace std;
int main() {
ifstream fin1("aaa.txt",ios::in);
if(!fin1)
{
cout<<"Can not open output file."<<endl;
exit(1);
}
char str[80];
fin1.getline(str,80);
cout<<str<<endl;
fin1.close();
return 0;
}
如图:
(2)编写程序,分别采用一次复制一个字符和一次复制一行的方法,实现将一个文本文件复制到另一个文本文件中。
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
//被复制文件的地址和目标地址自己决定
ifstream file_in("e:\\source.txt",ios::in);
ofstream file_out("e:\\target.txt",ios::out);
if(file_in.fail())
{
cout<<"文件source.txt打开失败!"<<endl;
return 1;
}
if(file_out.fail())
{
cout<<"文件target.txt打开失败!" <<endl;
return 1;
}
char nRead;
while(file_in>>nRead)
{
file_out<<nRead;
}
cout<<"copy成功!!!"<<endl;
file_in.close();
file_out.close();
return 0;
}