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

2021-11-29 10:25:47 浏览数 (2)

直接上代码:

代码语言: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;
}

0 人点赞