C++在读取和写入十六进制文件时出现问题
C++ having issues reading and writing Hex to file
所以我试图从一个十六进制文件中读取,修改十六进制值,将新的十六进制值写入一个新文件。然后打开新文件,再次修改十六进制并将其重写为第三个文件。我正在对十六进制值进行非常简单的加密。
我用来读取的函数如下:
vector<unsigned char> readFile(istream& file){
vector<unsigned char> returnValue;
//grab first 32 values from infile
for(int i = 0; i < 32 && !file.eof(); i++) {
returnValue.push_back(file.get());
}
return returnValue;
}
我用来写的函数如下:
void WriteVectorU8(ostream &file, vector<u8> bytes, bool isEncrypt){
for(int i = 0; i < bytes.size(); i++){
u8 byteToWrite = isEncrypt ? encrypt(bytes[i] , curKey[keyPointer]) : decrypt(bytes[i], curKey[keyPointer]);
incKeyPointer();
if(i != 0 && i%2 == 0){
file << " ";
}
file << hex << setw(2) << setfill('0') << int(byteToWrite);
}
file << endl;
}
以下是我打开文件的方式:
ofstream outFile;
outFile.open("tempName.bin", ios::binary);
我看到的是我打开的第一个文件被正确读取,IE文件.get()返回了一个有效的十六进制值。这方面的一个例子是文件中的值48ff,get()以十六进制检索48或以int检索72。我还可以看到我的加密文件是用十六进制正确写入的,但是当我去读我新创建的加密文件时,假设其中的第一个值是81a4,我只得到了第一个字符,"8"不是我期望的十六进制值"81",并且能够从我没有创建的第一个文件中得到。
ostream
的<<
运算符写入格式化文本,而不是原始数据。对于您正在尝试的内容,您需要使用ostream::write()
方法:
void WriteVectorU8(ostream &file, vector<u8> bytes, bool isEncrypt){
for(int i = 0; i < bytes.size(); i++){
u8 byteToWrite = isEncrypt ? encrypt(bytes[i] , curKey[keyPointer]) : decrypt(bytes[i], curKey[keyPointer]);
incKeyPointer();
file.write((char*)&byteToWrite, 1);
}
}
您在readFile()
函数中也滥用了eof()
(在尝试先读取某些内容之前,无法检查eof
)。它应该更像这样:
vector<unsigned char> readFile(istream& file){
vector<unsigned char> returnValue;
//grab first 32 values from infile
for(int i = 0; i < 32; i++) {
char ch = file.get();
if (!file) break;
returnValue.push_back(ch);
}
return returnValue;
}
或者:
vector<unsigned char> readFile(istream& file){
vector<unsigned char> returnValue;
//grab first 32 values from infile
char ch;
for(int i = 0; (i < 32) && (file.get(ch)); i++) {
returnValue.push_back(ch);
}
return returnValue;
}
相关文章:
- 使用mongocxx驱动程序时包含头文件问题
- 生成文件问题
- 从文件问题加载纹理 Android NDK 和 OpenGL
- Xcode 11 头文件问题
- 使用 c++ ifstream 读取文本文件问题
- 单独的类声明和方法定义文件问题
- C++生成文件问题
- 生成文件问题(体系结构x86_64的未定义符号:"_main",引用自:主可执行文件的隐式入口/启动)
- C++删除未使用的库的生成文件问题
- C++ 使文件问题
- 阅读矩阵市场文件C++问题
- 查找第一个文件问题无法使任何示例正常工作。
- "Recursive Makefile Considered Harmful"样式生成文件问题
- 标题文件问题中的类定义
- 嵌套 while 循环,包含文件 c++ 问题
- 几个制作文件问题
- 生成文件问题,获取"目标'rgbapixel.o'的配方失败"
- 从yaml文件问题opencv读取数据
- 类成员C++标头和 .cc 文件问题
- 添加选项以显示百分比时出现生成文件问题