C++11 为什么我的代码从w10_text.dat文件中分配了不必要的字节数?(OOP345塞内卡) void SecureData::backup(const char*文件){ 如果(!text) 抛出std::string(“\n***未存储数据***\n”); 如果(!已编码),则为else throw std::string(“\n***数据未编码***\n”); 否则{ //打开二进制文件 流的std::为; 打开(文件,std::ios::out); //在这里写二进制文件 如果(is.fail()) { 抛出std::string(“\n***无法打开任何文件”+std::string(文件)+“***\n”); } 其他的 { 对于(int i=0;itempchar; n字节++;/!”操作符是问题所在
用上面的代码替换了for外观。我认为“>>”操作符是问题所在C++11 为什么我的代码从w10_text.dat文件中分配了不必要的字节数?(OOP345塞内卡) void SecureData::backup(const char*文件){ 如果(!text) 抛出std::string(“\n***未存储数据***\n”); 如果(!已编码),则为else throw std::string(“\n***数据未编码***\n”); 否则{ //打开二进制文件 流的std::为; 打开(文件,std::ios::out); //在这里写二进制文件 如果(is.fail()) { 抛出std::string(“\n***无法打开任何文件”+std::string(文件)+“***\n”); } 其他的 { 对于(int i=0;itempchar; n字节++;/!”操作符是问题所在,c++11,C++11,用上面的代码替换了for外观。我认为“>>”操作符是问题所在 for(int i=0;i>文本[i];/!在此处读取二进制文件 }; void SecureData::backup(const char* file) { if (!text) throw std::string("\n***No data stored***\n"); else if (!encoded) throw std::string("\n**
for(int i=0;i>文本[i];/!在此处读取二进制文件
};
void SecureData::backup(const char* file) {
if (!text)
throw std::string("\n***No data stored***\n");
else if (!encoded)
throw std::string("\n***Data is not encoded***\n");
else {
// open binary file
std::ofstream is;
is.open(file, std::ios::out);
// write binary file here
if (is.fail())
{
throw std::string("\n***No file could be opened " + std::string(file) + " ***\n");
}
else
{
for (int i = 0; i < nbytes; i++)
{
is << text[i];
}
}
}
}
void SecureData::restore(const char* file, char key) {
// open binary file
std::ifstream os;
os.open(file, std::ios::in);
if (os.fail())
{
throw std::string("\n***No file could be opened " + std::string(file) + " ***\n");
}
else
{
nbytes = 0;
char tempchar = 0;
while (os.good())
{
os >> tempchar;
nbytes++; //!< count number of chars
}
std::cerr << nbytes << std::endl;
text = new char[nbytes]; //!< allocate memory here
os.clear();
os.seekg(0, std::ios::beg);
for (int i = 0; i < nbytes; i++)
{
os >> text[i]; //!< read binary file here
}
}
std::cout << "\n" << nbytes + 1 << " bytes copied from binary file "
<< file << " into memory (null byte included)\n";
encoded = true;
// decode using key
code(key);[enter image description here][1]
std::cout << "Data decrypted in memory\n\n";
}
os.read(text, nbytes);