我目前正在编写一个具有客户端-服务器架构(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::read
或ostream::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/