【问题标题】:How can I read and write unsigned chars to files with fstream in c++?如何在 c++ 中使用 fstream 读取和写入无符号字符到文件?
【发布时间】:2011-12-29 14:15:32
【问题描述】:

到目前为止,我有从 ifstream 读取无符号字符的代码:

ifstream in;
unsigned char temp;

in.open ("RANDOMFILE", ios::in | ios::binary);
in.read (&temp, 1);
in.close ();

这是正确的吗?我还尝试将 unsigned char 写入 ofstream:

ofstream out;
unsigned char temp;

out.open ("RANDOMFILE", ios::out | ios::binary);
out.write (&static_cast<char>(temp), 1);
out.close ();

但我得到以下写作错误:

error C2102: '&' requires l-value

还有这个阅读错误:

error C2664: 'std::basic_istream<_Elem,_Traits>::read' : cannot convert parameter 1 from 'unsigned char *' to 'char *'

如果有人能告诉我我的代码有什么问题,或者我如何从 fstream 读取和写入无符号字符,我们将不胜感激。

【问题讨论】:

    标签: c++ visual-c++


    【解决方案1】:

    写入错误告诉你,你正在使用static_cast创建的临时地址。

    代替:

    // Make a new char with the same value as temp
    out.write (&static_cast<char>(temp), 1);
    

    使用 temp 中已有的相同数据:

    // Use temp directly, interpreting it as a char
    out.write (reinterpret_cast<char*>(&temp), 1);
    

    如果您告诉编译器将数据解释为字符,也会修复读取错误

    in.read (reinterpret_cast<char*>(&temp), 1);
    

    【讨论】:

      【解决方案2】:

      read 函数始终将字节作为参数,为方便起见,表示为 char 值。您可以随意将指针投射到这些字节,所以

      in.read (reinterpret_cast<char*>(&temp), 1);
      

      将读取一个字节就好了。请记住,内存就是内存,C++ 的类型只是对内存的一种解释。当您将原始字节读入原始内存时(如read),您应该先读取,然后再转换为适当的类型。

      【讨论】:

        猜你喜欢
        • 2015-12-02
        • 1970-01-01
        • 2015-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-10
        相关资源
        最近更新 更多