在C++中以十六进制读取文件
Reading file as hex in C++
我目前正在编写一个具有客户端-服务器架构(TCP通信)的iOS应用程序。我现在正在服务器端编写一个模块,该模块应该以十六进制值读取声音文件,并将声音文件1024乘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;
}
}
我正在获取
二进制表达式("st::string"(又名'basic_string,allocater>')和'std::__1::ios_base&(std::__1::ios_base&)')
现在出现错误,我想这是编译器抱怨的原因,因为它不想逐字节读取std::字符串。然而,我不知道为什么。
如果你能帮我找到更好的方法,我会很高兴的。我也很想了解如何将文件拆分为1024字节的块。提前感谢!
不要对二进制文件使用格式化的流插入(<<)或提取(>>)运算符。
相反,请使用istream::read
或ostream::write
方法。
编辑1:块读取示例
#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;
由于OP还要求读取1K块,并希望警告不会产生成对十六进制数字的简单十六进制,因此这里有一个更全面的解决方案草案。错误处理是粗略的,但不应该被忽略。
#include <fstream>
#include <iostream>
#include <iomanip>
void process( char* buffer, size_t len ){
for( int i = 0; i < len; i++ ){
std::cout << std::setbase( 16 ) << std::setw( 2 ) << std::setfill( '0' )
<< (unsigned)buffer[i];
}
}
void sendfile( char * pathname ){
std::ifstream ifs( pathname, std::ifstream::in );
if( ifs.fail() ) throw "error opening";
const std::size_t BUFFER_SIZE = 1024;
char buffer [BUFFER_SIZE];
size_t nRead = 0;
while( ifs.read (buffer, sizeof(buffer)) ){
process( buffer, ifs.gcount() );
}
if( ! ifs.eof() ) throw "error reading";
process( buffer, ifs.gcount() );
ifs.close();
}
int main( int argc, char* args[] ){
if( 0 == argc ) throw "missing argument";
sendfile( args[1] );
}
相关文章:
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 读取文件的最后一行并输入到链接列表时出错
- 为什么在读取文件大小时文件IO速度会发生变化
- 读取文件时运行时的未知行为
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C++ 读取文件读取文件不正确
- 读取文件并将其存储在unordered_map中时出现问题
- 读取文件时无法使用 OpenMP 获得加速
- 使用istringstearm和get行缓慢读取文件
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 读取文件时引发异常
- 从标准输入读取文件后读取用户输入
- 在读取文件后重置句柄
- 如何在C++编译时读取文件?
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- 读取文件在第二次调用时返回INVALID_HANDLE
- 通过指针读取文件
- 逐行读取文件,并将数据插入变量和数组中