c++ 文件复制 往文件中输入字符、数字、字符串

1、将文件复制到另一个文件中

#include <fstream.h>
int main()
{
  char ch;
  ifstream f1 ("file_from");
  if(!f1)
  {
    cout<<"can not open 'file_from'for input"<<endl;
    return 1;
  }
ofstream f2("file_to");
  if(!f2)
  {
    cout<<"can not open 'file_to' for output."<<endl;
    return 1;

   }
  while(f2&&f1.get(ch)) f2.put(ch);
  f1.close();
  f2.close();
  return 0;
}


 


 

2、任意格式文件的复制

/*
	可以实现任意文件格式的复制
 */
#include <iostream>
using namespace std;
#define  length 100
int main()
{	
	//打开读文件
	FILE* file=NULL;
	// rb 只读方式打开一个二进制文件,文件必须存在
	file=fopen("Think Different.flv","rb");
	if(NULL==file)
	{
		cout<<"open read file fault!"<<endl;
		exit(1);
	}

	//打开写文件
	FILE* w_file;
	//wb 只写打开或新建一个二进制文件;只允许写数据
	w_file=fopen("Think DifferentFJ.flv","wb");
	if(NULL==file)
	{
			cout<<"open write file fault!"<<endl;
			exit(1);
	}
	
	//缓存字符串
	char buf[length];
	int nRead=0;
	bool TRUE=true;
	while(TRUE)
	{
		//nRead为实际中读取的字节数
		//fread以1个字节为单位,每次读取length个字节
		nRead=fread(&buf,1,length,file);
		//nRead<length,说明即将读取结束 
		if(nRead<length)
			TRUE=false;
		//将buf中的数据写入文件
		fwrite(&buf,1,nRead,w_file);

	
	}
	//关闭写文件
	fclose(w_file);
	//关闭读文件
	fclose(file);
	return 0;
}


 

 

3、把一个整数,一个浮点数和一个串写到test文件中

#include <iostream>

#include <fstream>
using namespace std;
int main()
{
  ofstream outfile ("test.txt");
  if(!outfile)
  {
    cout<<"can not open file"<<endl;
    return 1;
  }
 outfile<<19<<"/t"<<123.23<<"/t";
 outfile<<"this is a short text file"<<endl;
 outfile.close();
 
 return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值