文件复制……

本文提供两个C++示例程序,演示如何复制文本文件及二进制文件。首先通过字符流实现文本文件的逐行复制;接着使用缓冲区一次性读取整个文件内容的方式复制二进制文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题链接……

 

复制文本类文件:

#include"iostream"
#include"string"
#include"fstream"
#include"stdlib.h"
using namespace std;
int main()
{ 
    fstream file;
    char filename[512];

    cout<<"打开文件:";
    cin>>filename;
    file.open(filename,ifstream::in);

    if(!file.is_open())
    {
        cout<<"文件不在在!"<<endl;
        exit(1);
    }
    else  
    {
        string str;
        ofstream anotherfile("d:\\fanyajing.txt");
        while(!file.eof())    
        {
            getline(file,str);
            anotherfile<<str<<endl;    
        }
        anotherfile.close();        
    }
    
    return 0;
}

 

复制任何格式文件:

#include <iostream>
#include <fstream>
using namespace std;

int main () 
{
    int length;
    char * buffer;
    char filename[512];
    ifstream infile;
    ofstream outfile;

    cout<<"打开文件:";
    cin>>filename;
    infile.open (filename, ifstream::binary );    
    if(!infile.is_open())
    {
        cout<<"文件不存在"<<endl;
        return 0;
    }

    // 获取文件长度:
    infile.seekg (0, ios::end);
    length = infile.tellg();
    infile.seekg (0, ios::beg);

    // 分配内存空间:
    buffer = new char [length];

    // 读取块数据:
    infile.read (buffer,length);
    infile.close();

    //复制保存文件:
    outfile.open("c:\\out.jpg",ofstream::binary);    //不同格式图片改不同扩展名就OK!
    outfile.write (buffer,length);

    delete[] buffer;
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值