【发布时间】:2013-03-20 11:49:30
【问题描述】:
我正在用 Visual Studio C++ 编写一个简单的控制台应用程序。我想读取一个带有.cer 扩展名的二进制文件到一个字节数组。
ifstream inFile;
size_t size = 0;
char* oData = 0;
inFile.open(path, ios::in|ios::binary);
if (inFile.is_open())
{
size = inFile.tellg(); // get the length of the file
oData = new char[size+1]; // for the '\0'
inFile.read( oData, size );
oData[size] = '\0' ; // set '\0'
inFile.close();
buff.CryptoContext = (byte*)oData;
delete[] oData;
}
但是当我启动它时,我在所有oData 字符中收到相同的字符,每次都是另一个,例如:
oData = "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@...".
然后我尝试了另一种方法:
std::ifstream in(path, std::ios::in | std::ios::binary);
if (in)
{
std::string contents;
in.seekg(0, std::ios::end);
contents.resize(in.tellg());
in.seekg(0, std::ios::beg);
in.read(&contents[0], contents.size());
in.close();
}
现在内容有很奇怪的值:一部分是正确的,一部分是负数和奇怪的值(可能和signed char和unsigned char有关?)。
有人知道吗?
先谢谢了!
【问题讨论】:
-
in.read( &contents[0], contents.size() )行可能未定义的行为,绝对是一个非常糟糕的主意。
标签: c++ file binary ifstream cer