前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++ fstream 二进制读写文件 (一个文件备份的例子)

C++ fstream 二进制读写文件 (一个文件备份的例子)

作者头像
xcywt
发布2021-11-29 10:25:47
2.9K0
发布2021-11-29 10:25:47
举报
文章被收录于专栏:xcywt

直接上代码:

代码语言:javascript
复制
#include <iostream>
#include <string>
#include <vector>
#include <fstream>

bool ReadFile(std::string& strFile, std::vector<char>& buffer)
{
    std::ifstream infile(strFile.c_str(), std::ifstream::binary);
    if (!infile.is_open())
    {
        printf("Read File:%s Error ... \n", strFile.c_str());
        return false;
    }

    // 获取文件大小
    infile.seekg(0, std::ifstream::end);
    long size = infile.tellg();
    infile.seekg(0);

    buffer.resize(size);
    printf("文件:[%s] 共有:%ld(字节) ..... \n", strFile.c_str(), size);

    // read content of infile
    infile.read(&buffer[0], size);
    infile.close();
    return true;
}

bool WriteFile(std::string& strFile, std::vector<char>& buffer)
{
    std::ofstream outfile(strFile.c_str(), std::ifstream::binary);
    if (!outfile.is_open())
    {
        printf("Write File:%s Error ... \n", strFile.c_str());
        return false;
    }
    outfile.write(&buffer[0], buffer.size());
    outfile.close();
    return true;
}

void test1126_222()
{
    std::string oldFile = "test.txt";
    std::vector<char> buffer;
    if (ReadFile(oldFile, buffer))
    {
        std::string newFile("test_new.txt");
        if (WriteFile(newFile, buffer))
        {
            printf("备份文件 %s --> %s 成功 ... \n", oldFile.c_str(), newFile.c_str());
        }
    }
}

int main()
{
    test1126_222();
    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-11-26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档