C++ 如何将一个文件里的数据写入到另一个文件里?

打个比方(文件内容如下)
学号 姓名 成绩
123 aa 90
124 bb 90
125 cc 90
如何将这个文件的内容写入到另外一个文件,并且在执行操作时将数据输出到显示屏上。
说下思路和所需要用到的函数就行
谢谢啦

C++ 实现文件复制的方法为:

    文件操作需要用到头函数fstream

    用ifstream打开源文件,备读

    用ofstream打开目标文件,备写

    循环读取源文件

      用getline()函数,逐行读取源文件到字符串中

      用cout输出字符串到标准输出(屏幕)

      把读到的字符输出到目标文件

      若读文件结束,结束循环

    关闭源文件和目标文件

参考代码:

#include<iostream> //输入输出流
#include<fstream> //文件流头文件
using namespace std;
int main()
{
ifstream in("src.txt"); //源文件读
ofstream out( "obj.txt" ); //目标文件写
if (!in){
cout <<"open source file error!"<<endl;
return -1;
}
while( !in.eof() ) //文件未结束,循环
{
char str[1024];
in.getline(str,sizeof(str),'\n'); //读一行
cout << str << endl; //输出到屏幕
out<< str <<endl; //输出到文件
}
in.close();
out.close();
return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-10-02
#include <IOSTREAM.H>
#include <FSTREAM.H>
class information
{
public:
int number;
char name[10];
int score;
};
void main()
{
information a[2];
for(int i=0;i<2;i++)
{
cout<<"姓名:"<<endl;
cin>>a[i].name;
cout<<"学号:"<<endl;
cin>>a[i].number;
cout<<"成绩:"<<endl;
cin>>a[i].score;
}

//文件写入
fstream finout;
finout.open("stu_info.txt",ios::out|ios::app);

finout<<"姓名\t"<<"学号\t"<<"成绩\t"<<endl;

for(i=0;i<2;i++)
{
finout<<a[i].name<<"\t"<<a[i].number<<"\t"<<a[i].score<<endl;
}
finout.close();
// 文件读取
char c;
fstream read1;
read1.open("stu_info.txt",ios::in);
while(!read1.eof())
{
c=read1.get();
cout<<(char)c;
}
read1.close();
}本回答被提问者采纳
第2个回答  2011-09-13
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ofstream fout("新文件.txt");
ifstream fin("旧文件.txt");
char ch;
while((ch = fin.get()) && (ch != EOF))
{
cout << ch;
fout << ch;
}
return 0;
}
相似回答