C++实现文件复制

这一小节主要是文件的读写操作,头文件fstream,其中读和写主要对应ifstream和ofstream,打开文件夹时,主要有以下几种模式:

ios::in    打开一个可读文件

ios::out    打开一个可写文件

ios::binary    以二进制的形式打开一个文件

ios::app    写入的所有数据将被加到文件末尾

ios::trunk    删除文件原来已有的内容,再写入

ios::nocreate    如果要打开的文件夹不存将报错

ios::noreplece    如果打开的文件夹存在将报错

先看实现文件复制的程序:

// helloworld.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<fstream>  
#include<iostream>

using namespace std;

int main()
{
	ifstream in;
	ofstream out;
	in.open("shuru.txt");		//读取文件
	out.open("shuchu.txt");
	if (!in)
	{
		cerr << "打开失败!" << endl;
		return 0;
	}
	if (!out)
	{
		cerr << "打开失败!" << endl;
		return 0;
	}
	char x;		
	while (in >> x)			//将文件“shuru”复制生成新的文件“输出”
	{
		out <<x;
	}
	out << endl;
	out.close();
	in.close();
	return 0;
}

运行前再目录下新建一个“shuru”文档:


运行程序:


接下来讨论文件的不同打开模式:

将语句:

out.open("shuchu.txt");

替换为:

out.open("shuchu.txt",ios::app);

再运行:


输出内容在原来内容末尾继续。其他的模式使用类似。



 
 


猜你喜欢

转载自blog.csdn.net/Meixueer_Lily/article/details/79648709