C++基础知识(1)----文件操作

   参照 小菜鸟上校 的博客

  

 1 // file operat.cpp : 定义控制台应用程序的入口点。
 2 /*上述例子的主要功能是将一个文件的内容复制到另一个文件中,
 3 这个功能主要由一个函数copy来实现。它包含了两个string类型的参数,s和d,表示将文件s的内容复制到文件d中。
 4 首先声明了两个文件流,ifstream infile和ofstream outfile,然后调用流的open方法打开文件,
 5 并检查是否在打开的过程中出了问题。若果有问题则报错并返回,否则的话,进行就开始进行复制。
 6 可以看到,我们每次将源文件的内容取出一行放到一个临时的字符串变量temp中,然后再将temp的内容写入到目的文件中。
 7 函数getline是一个顶层函数,它的作用是从输入流中读取一行,并且放入到一个字符串变量中。*/
 8 
 9 //
10 
11 #include "stdafx.h"
12 #include <fstream>
13 #include <iostream>
14 #include <string>
15 
16 using namespace std;
17 
18 
19 void copy(string s, string d)   //string 类型的参数,表示将s 的内容复制到 d
20 {
21     //声明俩个文件输入输出流
22     ifstream infile;
23     ofstream outfile;
24 
25     infile.open(s.c_str());  //打开文件
26     if (!infile)
27     {
28         cout << "file: " << "not find!" << endl;    //原文件不存在则报错
29         return;
30     }
31     outfile.open( d.c_str());
32     if (!outfile)
33     {
34         cout << "file: " << d << "not find!" << endl;
35         return;
36     }
37 
38     string temp = "";
39     while (getline(infile, temp))    //把infile 中的内容 复制到temp
40     {
41         outfile << temp << "
";      //把复制到的temp内容在outfile 中显示
42     }
43 
44     //关闭文件
45     infile.close();
46     outfile.close();
47     cout << "one file copy finished!" << endl;
48 }
49 
50 
51 void main()
52 { 
53     string source = "C:\Users\Administrator\Desktop\source.txt";
54     string destination = "C:\Users\Administrator\Desktop\destination.txt";
55     copy(source,destination);
56     
57 }

    需要注意的是 文件的路径写法 :VS中要双斜线 \    ,,而不能是单斜线  。。。

  亲测可运行。。。。。

原文地址:https://www.cnblogs.com/wyuzl/p/6165933.html