【问题标题】:C++ having issues reading and writing Hex to fileC++ 在读取和写入 Hex 到文件时遇到问题
【发布时间】:2015-02-16 23:11:17
【问题描述】:

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

我用来阅读的功能是休闲:

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

我用来写的函数是fallows:

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

我看到的是我打开的第一个文件被正确读取,即 file.get() 返回一个有效的十六进制值。 这方面的一个例子是文件中的值 48ff,get() 检索 48 十六进制或 72 作为 int。 我还可以看到我的加密文件是以十六进制正确写入的,但是当我去读取我新创建的加密文件时,可以说其中的第一个值是 81a4 我只得到第一个字符,'8'而不是十六进制我期望的值“81”,并且能够从我没有创建的第一个文件中获取。

【问题讨论】:

    标签: c++ encryption hex iostream


    【解决方案1】:

    ostream&lt;&lt; operator 写入格式化文本,而不是原始数据。对于您正在尝试的内容,您需要改用 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;
    }
    

    【讨论】:

    • 您是否还建议在我的 readFile 函数中使用 file.read() 还是不会有所作为?
    • 在这种特殊情况下,没关系。 char ch = file.get()char ch; file.read((char*)&amp;ch, 1) 将返回相同的数据。由于您没有使用 &gt;&gt; 运算符,因此您没有解析格式化文本。 get()read() 都在读取原始二进制数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-28
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多