4、C++ 实现文件复制(类实现)

//代码测试 运行环境vc++2010
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class ClsCopyfile{
public :
    ClsCopyfile(char * sfile="",char * dfile="");
    ifstream & funGetInFile();
    ofstream & funGetOutFile();
    friend istream & operator>>(istream & stream,ClsCopyfile & copys)
    {
        string name;
        cout<<"请输入源文件名称(可加路径):"<<endl;
         stream.getline(copys.m_strSource_file,256);
        cout<<"请输入目标文件名称(可加路径):"<<endl;
         stream.getline(copys.m_strDect_file,256);
        return stream;
    }
    int funCopyFile();
private:
    char m_strSource_file[256];
    char m_strDect_file[256];
    char buff[4096];
};
ClsCopyfile::ClsCopyfile(char sfile[256],char  dfile[256])
{
    strcpy(m_strSource_file,sfile);
    strcpy(m_strDect_file,dfile);
}
ifstream & ClsCopyfile::funGetInFile()
{
    //new 返回是一内存地址. 如果不用new 则不能使用局部变量当作引用
    ifstream & in_file=*(new ifstream(m_strSource_file,ios::in|ios::binary));//两个流对象同时采用二进制方式
     return in_file;
}
ofstream & ClsCopyfile::funGetOutFile()
{
//也可以用静态局部变量 static ofstream copy_file(m_strDect_file,ios::binary|ios::trunc|ios::out);
    ofstream ©_file=*(new ofstream(m_strDect_file,ios::binary|ios::trunc|ios::out)); // 若加ios::trunc//与文件创建链接,如果文件不存在,则创建文件,文件存在,先删除原文件再创建
    return copy_file;
}
int ClsCopyfile::funCopyFile()
{
    ifstream  &in=funGetInFile();//如果不使用 &in会报错,在vs2008以后 从“类”创建的对象无法访问该“类”的 protected 或 private 成员,不可以执行拷贝构造函数
    if(!in)
    {
        cout<<"文件不存在!"<<endl;
         return 0;
    }
    else
    {
        ofstream &out=funGetOutFile();
        if(!out)
        {
            cout<<"复制数据失败!"<<endl;
             return 0;
        }
        else
        {
            int n=0;
            while(!in.eof())//没有到文件末尾
            {
                in.read(buff,4096);
                n=int(in.gcount());//实际读取数
                out.write(buff,n);
            }
            out.close();
        }
    }
    in.close();
    return 1;
    
}
int main()
{
    ClsCopyfile copy;
    cin>>copy;
    if(copy.funCopyFile())
    {
        cout<<"数据复制成功!"<<endl;
     }
    return 0;
}
//new 是动态分配堆内存,返回的是指针(内存地址),在程序退出之前,不用delete释放内存,则不会自动释放,程序结束自动释放。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值