c++ - 在 C++ 中以十六进制读取文件

标签 c++ c++11 file-io tcp ifstream

我目前正在编写一个具有客户端-服务器架构(TCP 通信)的 iOS 应用程序。我现在正在服务器端编写一个模块,该模块应该以十六进制值的形式读取声音文件,并将 1024 x 1024 字节的声音文件发送到客户端。

我不是经验丰富的 C++ 开发人员,我在阅读文件方面需要一些帮助。现在我的代码是:

void PacketInterpreter::sendFile(int turn, int gameID){
    std::string absoluteFilePath = (std::to_string(gameID) + "/sound.caf");
    unsigned char x;

    std::ifstream file(absoluteFilePath, std::ios::binary);
    file >> std::noskipws;

    std::string outstream;

    while(file >> x){
        outstream << std::hex << (int)x;
    }
}

我得到了

Invalid operands to binary expression ('std::string' (aka 'basic_string, allocator >') and 'std::__1::ios_base &(std::__1::ios_base &)')

现在出错了,我发现这是编译器的提示,因为它不想逐字节读入 std::string。但是,我不知道为什么。

如果你能帮我找到更好的方法来做这件事,我会很高兴。我也喜欢关于如何将文件拆分为 1024 字节 block 的一些输入。提前致谢!

最佳答案

不要对二进制文件使用格式化流插入 (<<) 或提取 (>>) 运算符。

相反,使用istream::readostream::write 方法。

编辑 1: block 读取示例。

#define BUFFER_CAPACITY 512
unsigned char buffer[BUFFER_CAPACITY];
ifstream input_data("my_data.caf");
input_data.read((unsigned char)&buffer[0], sizeof(buffer));
//...
cout << "Look, first by is "
     << "0x" << hex << buffer[0]
     << " or as decimal: " << dec << buffer[0]
     << endl;

关于c++ - 在 C++ 中以十六进制读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20336810/

相关文章:

c++ - C 中的 volatile 关键字是否正确需要特殊的硬件支持才能工作?

c++ - 在 Qt 中更改 XML 标记的属性值

c++ - CFLAGS=-std=c++11 -O3 -Wall -pedantic 在 makefile 中未被识别

c - 用C语言读取多个文本文件

asp.net - 在 ASP.NET 中以中等信任度存储临时用户文件

javascript - 如何使用 XUL 读/写文件?

c++ - 使用 int 数组作为键的二叉树(欧氏距离)?

c# - 我可以使用 C++ 从 C# BHO 遍历 DOM 吗?

C++ 什么是 std::shared_future 和 std::promise

c++ - `weak_ptr` 和 `shared_ptr` 访问如何是原子的