C++在读取和写入十六进制文件时出现问题

C++ having issues reading and writing Hex to file

本文关键字:文件 问题 十六进制 读取 C++      更新时间:2023-10-16

所以我试图从一个十六进制文件中读取,修改十六进制值,将新的十六进制值写入一个新文件。然后打开新文件,再次修改十六进制并将其重写为第三个文件。我正在对十六进制值进行非常简单的加密。

我用来读取的函数如下:

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;
}