参照 小菜鸟上校 的博客
// file operat.cpp : 定义控制台应用程序的入口点。
/*上述例子的主要功能是将一个文件的内容复制到另一个文件中,
这个功能主要由一个函数copy来实现。它包含了两个string类型的参数,s和d,表示将文件s的内容复制到文件d中。
首先声明了两个文件流,ifstream infile和ofstream outfile,然后调用流的open方法打开文件,
并检查是否在打开的过程中出了问题。若果有问题则报错并返回,否则的话,进行就开始进行复制。
可以看到,我们每次将源文件的内容取出一行放到一个临时的字符串变量temp中,然后再将temp的内容写入到目的文件中。
函数getline是一个顶层函数,它的作用是从输入流中读取一行,并且放入到一个字符串变量中。*/ // #include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string> using namespace std; void copy(string s, string d) //string 类型的参数,表示将s 的内容复制到 d
{
//声明俩个文件输入输出流
ifstream infile;
ofstream outfile; infile.open(s.c_str()); //打开文件
if (!infile)
{
cout << "file: " << "not find!" << endl; //原文件不存在则报错
return;
}
outfile.open( d.c_str());
if (!outfile)
{
cout << "file: " << d << "not find!" << endl;
return;
} string temp = "";
while (getline(infile, temp)) //把infile 中的内容 复制到temp
{
outfile << temp << "\n"; //把复制到的temp内容在outfile 中显示
} //关闭文件
infile.close();
outfile.close();
cout << "one file copy finished!" << endl;
} void main()
{
string source = "C:\\Users\\Administrator\\Desktop\\source.txt";
string destination = "C:\\Users\\Administrator\\Desktop\\destination.txt";
copy(source,destination); }
需要注意的是 文件的路径写法 :VS中要双斜线 \\ ,,而不能是单斜线 \ 。。。
亲测可运行。。。。。