我在 visual studio 2019 中用 c++ 编写的函数有问题:
#include <fstream>
//whatever...
void xorcrypt(string filename) { //the function
ifstream inFile(filename, ios::ate);
ifstream::pos_type size = inFile.tellg();
char* memblock;
memblock = new char[(unsigned int)size];
inFile.seekg(0, ios::beg);
inFile.read(memblock, size);
inFile.close();
for (long long i = 0; i < size;)
for (int x = 0; x <= 255 && i < size; ++i, ++x)
memblock[i] ^= x; //xor operation
ofstream outFile;
outFile.open(filename, ios::trunc);
for (long long i = 0; i < size; ++i)
outFile << memblock[i]; //The Problem
outFile.close();
delete[] memblock;
}
这段代码是有问题的,因为 Visual Studio 说我的动态初始化缓冲区, 它包含文件的全部内容,可能会向文件写入 2 个字节而不是 1 个字节...... 我不知道为什么会发生这种情况,并且大多数时候“XORcrypts”我的文件的功能是正确的, 所以我希望其他人可能知道为什么会这样。
上面显示的代码获取一个文件,打开它以供读取,并将内容转储到一个动态初始化的 char 数组中,然后文件被关闭、截断(删除),然后使用一个代码块,每个字节递增 XOR 操作,用于字符。写操作完成后,它会删除字符数组并关闭文件。
如果可能的话,我希望有一个解决方案不会产生比基础 c++ 和 fstream 更多的依赖性。提前致谢。
最佳答案
出现警告是因为编译器无法判断size
的值是什么可能!如果文件为空,可能小于 1(或 2)。将您的分配更改为以下内容,以避免警告:
memblock = new char[std::max((unsigned int)size, 2u)];
(当然,您需要 #include <algorithm>
才能获得 std::max()
。)
编辑:为清楚起见,这是我在没有“修复”的情况下收到的警告:
warning C6385: Reading invalid data from 'memblock': the readable size is '(unsigned int)size.public: __cdecl std::fpos<struct _Mbstatet>::operator __int64(void)const ()*1' bytes, but '2' bytes may be read.
埃里克,这和你看到的一样吗?
关于c++ - 在 C++ 代码部分,可能会写入两个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57944124/