如何读取和写入无符号字符到cstream中的fstream文件? [英] How can I read and write unsigned chars to files with fstream in c++?

查看:675
本文介绍了如何读取和写入无符号字符到cstream中的fstream文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我有代码从ifstream读取一个unsigned char:

So far I have code to read an unsigned char from ifstream:

ifstream in;
unsigned char temp;

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

这是否正确?我也尝试写一个unsigned char到一个流:

Is this correct? I also tried to write an unsigned char to an ofstream:

ofstream out;
unsigned char temp;

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

但我写作时遇到以下错误:

But I get the following error for writing:

error C2102: '&' requires l-value

此错误用于阅读:

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

可以告诉我我的代码有什么问题,或者如何从fstream读取和写入unsigned chars。

It would be appreciated if someone could tell me what's wrong with my code or how I can read and write unsigned chars from fstream.

推荐答案

错误告诉您您正在使用由 static_cast 创建的临时地址。

The write error is telling you that you are taking the address of the temporary created by static_cast.

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

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

Use the same data already in temp:

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

如果你告诉编译器解释,读错误数据作为char:

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

这篇关于如何读取和写入无符号字符到cstream中的fstream文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆