zoukankan      html  css  js  c++  java
  • C++ fstream 二进制读写文件 (一个文件备份的例子)

    直接上代码:

    #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;
    }
  • 相关阅读:
    Mybatis批处理
    Mybatis兼容C3P0连接池
    一对多,多对一查询
    缓存
    动态sql
    mybatis 日志记录
    python学习day07-encode和decode
    python学习day07---三级目录优化
    python学习day06练习---三级目录
    python学习day06--02字典增删差改以及字符串的一些方法
  • 原文地址:https://www.cnblogs.com/xcywt/p/15606762.html
Copyright © 2011-2022 走看看