【问题标题】:Problems while trying to Read Binary File C++尝试读取二进制文件 C++ 时出现问题
【发布时间】: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 charunsigned char有关?)。

有人知道吗?

先谢谢了!

【问题讨论】:

  • in.read( &contents[0], contents.size() )可能未定义的行为,绝对是一个非常糟糕的主意。

标签: c++ file binary ifstream cer


【解决方案1】:

看第一个版本:

是什么让您认为tellg 获得了流的大小?它没有,它returns the current read position。然后您继续将指向您的数据的指针指向buff.CryptoContents 并立即删除指向的数据!这是非常危险的做法;您需要复制数据、使用智能指针或以其他方式确保数据具有正确的生命周期。如果您在调试模式下运行,则删除可能会使用标记来显示数据已被删除,这就是您获得相同字符流的原因。

我怀疑您关于已签名和未签名的建议可能是正确的,但我不能在没有看到您的文件和数据的情况下说。

【讨论】:

    【解决方案2】:

    您将 CryptoContext 设置为通过 byte 指针指向您的数据,然后删除该数据!

    buff.CryptoContext = (byte*)oData;
    delete[] oData;
    

    在这行之后 CryptoContext 指向已释放和无效的数据。只需将oData 数组在内存中保留更长的时间,并在完成解码或使用它进行任何操作后将其删除。

    【讨论】:

      猜你喜欢
      • 2013-03-23
      • 2011-03-30
      • 2011-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-01
      相关资源
      最近更新 更多