温馨提示×

C++ byte数组与文件IO操作

c++
小樊
101
2024-07-13 17:36:29
栏目: 编程语言

在C++中,可以使用std::fstream类来进行文件IO操作。下面是一个示例代码,演示了如何将byte数组写入文件并读取文件中的内容到byte数组中:

#include <iostream>
#include <fstream>
#include <vector>

int main() {
    // 创建一个byte数组
    std::vector<unsigned char> data = {0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64};

    // 将byte数组写入文件
    std::ofstream outfile("data.bin", std::ios::binary);
    if (outfile.is_open()) {
        outfile.write(reinterpret_cast<const char*>(data.data()), data.size());
        outfile.close();
    } else {
        std::cerr << "Error opening file for writing" << std::endl;
        return 1;
    }

    // 从文件中读取内容到byte数组中
    std::ifstream infile("data.bin", std::ios::binary);
    if (infile.is_open()) {
        infile.seekg(0, std::ios::end);
        std::streampos fileSize = infile.tellg();
        infile.seekg(0, std::ios::beg);

        std::vector<unsigned char> readData(fileSize);
        infile.read(reinterpret_cast<char*>(readData.data()), fileSize);
        infile.close();

        // 打印读取的内容
        for (unsigned char c : readData) {
            std::cout << c;
        }
        std::cout << std::endl;
    } else {
        std::cerr << "Error opening file for reading" << std::endl;
        return 1;
    }

    return 0;
}

在上面的示例中,首先创建了一个包含一些ASCII字符的byte数组data。然后将这个byte数组写入名为"data.bin"的二进制文件中。接着从文件中读取内容并存储到另一个byte数组readData中,最后打印读取的内容。

0