最简短的文件拷贝C++代码

本文提供了一个使用C++标准库中的fstream实现文件复制的示例代码。通过该示例,读者可以了解到如何利用ifstream和ofstream进行文件读写操作,并且了解如何检查文件操作的状态。

#include <cstdio>
#include <fstream>

int main(int argc, char * argv[])
{
    if (3 != argc)
    {
        printf("usage: %s src dst\n", argv[0]);
        return(1);
    }

    std::ifstream ifs(argv[1], std::ios::binary);
    if (!ifs.is_open())
    {
        printf("open %s failed\n", argv[1]);
        return(2);
    }

    std::ofstream ofs(argv[2], std::ios::binary | std::ios::trunc);
    if (!ofs.is_open())
    {
        printf("create %s failed\n", argv[2]);
        return(3);
    }

    ofs << ifs.rdbuf();

    ofs.close();
    ifs.close();

    return(0);
}


既然使用了fstream,说个问题:判断文件是否正常打开时,用对象来判断是不对的,应该用is_open函数。

 

再压缩下代码:

#include <fstream>

int main(int argc, char * argv[])
{
    if (3 != argc)
    {
        printf("usage: %s src dst\n", argv[0]);
        return(1);
    }

    std::ofstream(argv[2]) << std::ifstream(argv[1]).rdbuf();

    return(0);
}


 

 


### C++ 实现文件拷贝功能的代码示例 以下是基于标准库 `std::ifstream` 和 `std::ofstream` 的 C++ 文件拷贝功能实现。此方法适用于二进制文件和文本文件。 #### 使用缓冲区逐块读写的方式进行文件拷贝 这种方法通过设置一个固定大小的缓冲区来逐步读取源文件的内容并将其写入到目标文件中,从而减少内存占用并提高效率。 ```cpp #include <iostream> #include <fstream> void copyFile(const std::string& srcFilePath, const std::string& destFilePath) { // 定义缓冲区大小(可以根据需求调整) constexpr size_t bufferSize = 4096; char buffer[bufferSize]; // 打开源文件(输入流),以二进制模式读取 std::ifstream source(srcFilePath, std::ios::binary); if (!source.is_open()) { std::cerr << "无法打开源文件:" << srcFilePath << std::endl; return; } // 打开目标文件(输出流),以二进制模式写入 std::ofstream destination(destFilePath, std::ios::binary | std::ios::trunc); if (!destination.is_open()) { std::cerr << "无法创建目标文件:" << destFilePath << std::endl; source.close(); return; } // 循环读取源文件内容并写入目标文件 while (source.read(buffer, sizeof(buffer))) { destination.write(buffer, sizeof(buffer)); } // 处理剩余未满缓冲区的数据 if (!source.eof()) { std::cerr << "读取文件时发生错误" << std::endl; } else { size_t bytesLeft = source.gcount(); // 获取后一次实际读取的字节数 destination.write(buffer, bytesLeft); } // 关闭文件流 source.close(); destination.close(); std::cout << "文件已成功复制:" << srcFilePath << " -> " << destFilePath << std::endl; } ``` #### 主程序调用示例 以下是如何调用上述函数的一个简单例子: ```cpp int main() { std::string srcPath = "example.txt"; std::string dstPath = "copied_example.txt"; copyFile(srcPath, dstPath); return 0; } ``` --- ### 功能说明 1. **二进制模式**:为了支持各种类型的文件(如图片、视频等),使用了二进制模式 (`std::ios::binary`) 来处理文件。 2. **缓冲区机制**:为了避免一次性加载整个大文件进入内存,采用了固定大小的缓冲区逐块读写数据[^3]。 3. **异常处理**:在打开文件失败的情况下提供了基本的日志提示,并关闭已经打开的资源以释放系统资源。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值