Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 读写字节_C++_Visual C++ - Fatal编程技术网

C++ 读写字节

C++ 读写字节,c++,visual-c++,C++,Visual C++,我需要对任何格式的XOR文件进行加密,为此我必须逐个读取文件中的字节组,对它们进行加密,然后将结果写入输出文件 如何组织读取和写入字节?您可以逐个读取,但我建议读取和写入字节块。Performance wise能够更好地尽可能少地访问文件,而且操作速度慢。根据内存约束,可以将第二个示例代码的块大小(实际为1024)增加到所需的字节数 示例代码,逐个加密: #include <iostream> #include <fstream> #include <vector&

我需要对任何格式的XOR文件进行加密,为此我必须逐个读取文件中的字节组,对它们进行加密,然后将结果写入输出文件


如何组织读取和写入字节?

您可以逐个读取,但我建议读取和写入字节块。Performance wise能够更好地尽可能少地访问文件,而且操作速度慢。根据内存约束,可以将第二个示例代码的块大小(实际为1024)增加到所需的字节数

示例代码,逐个加密:

#include <iostream>
#include <fstream>
#include <vector>

int main(int argc, char* argv[]) {
    char bytes;
    std::ifstream ifs("ficheroentrada", std::ios_base::binary);
    std::ofstream ofs("ficherosalida", std::ios_base::binary);
    while (!ifs.eof()) {
        ifs.get(bytes);
        bytes ^= 0xAA; // xor constant or variable
        ofs.put(bytes);
    }
    ifs.close();
    ofs.close();

    return 0;
}
使用XOR的块加密代码更推荐使用此代码

#include <iostream>
#include <fstream>
#include <vector>

int main(int argc, char* argv[]) {
    std::vector<char> bytes(1024); // change the block size
    std::ifstream ifs("e:\\save_out.txt", std::ios_base::binary);
    std::ofstream ofs("e:\\save_out2.txt", std::ios_base::binary);
    while (!ifs.eof()) {
        ifs.read((char*)&bytes[0], bytes.size());
        unsigned int size_read = ifs.gcount();
        for (unsigned int idx = 0; idx < size_read; idx++) {
            bytes[idx] ^= 0xAA; // xor constant or variable
        }
        ofs.write((char*)&bytes[0], size_read);
    }
    ifs.close();
    ofs.close();

    return 0;
}

你是在问如何读写文件吗?你可以从一本关于C++的好书或教程开始。首先,即使您一次从流中读取一个字符,流也会缓冲。按块读取可能会稍微快一点,但可能不是很明显。仅使用ifs.get和ofs.put不会明显减慢速度。当然,使用ifs.eof作为循环条件是错误的;在第一个示例中,它将导致额外读取一个字节。此外,除非您事后检查状态,否则没有结束点。是的,确实流将缓冲,但缓冲大小以及缓冲是否会受到其他程序的影响没有控制。感谢get and put更新、close调用确实没有必要,但我喜欢显式调用,有任何相反的原因,不调用?很有效!非常感谢@NetVipeC通常,最好将缓冲区留给流;实现应该为平台选择最佳值。