[英]read() function in c++ similar to c read()
Is there any method equivalent to c read()
in c++? 有什么等效于c ++中的c read()
方法吗? To illustrate my question, in C, if I have: 为了说明我的问题,如果我有C,请使用C:
struct A{
char data[4];
int num;
};
...and if I use: ...如果我使用:
A* a = malloc (sizeof(struct A));
read (fd, a, sizeof(struct A));
I can directly populate my struct. 我可以直接填充我的结构。 Is there a way in c++ to achieve this without using c read() method? c ++中有没有一种方法可以在不使用c read()方法的情况下实现这一目标? Methods in std::istream
need char*
as an argument, is there any method which takes void*
as an argument? std::istream
方法需要char*
作为参数,是否有任何将void*
作为参数的方法?
The closest equivalent is almost certainly to use istream::read
: 最接近的等效方法几乎可以肯定是使用istream::read
:
struct A {
char data[4];
int num;
};
A a;
std::ifstream in("somefile", std::ios::binary);
in.read((char *)&a, sizeof(a));
Note that this is equivalent to read
in a number of ways you'd probably prefer it wasn't--for example, it'll probably break if you upgrade your compiler, and might break just from breathing a little wrong. 请注意,这等效于您可能不希望以多种方式read
的内容-例如,如果升级编译器,它可能会中断,并且可能会因呼吸错误而中断。
If you insist on doing it anyway, you probably at least want to hide the ugliness a little: 如果您仍然坚持这样做,那么您可能至少想稍微掩盖丑陋之处:
struct A {
char data[4];
int num;
friend std::istream &operator>>(std::istream &is, A &a) {
return is.read((char *)a, sizeof(a));
}
};
Then other code will read an instance from a file with a normal insertion operator: 然后其他代码将使用普通的插入运算符从文件中读取实例:
std::ofstream in("whatever", std::ios:;binary);
A a;
in >> a;
This way, when you come to your senses and serialize your object a little more sanely, you'll only need to modify operator>>
, and the rest of the code will remain unchanged. 这样,当您感觉到并理智地序列化对象时,只需要修改operator>>
,其余代码将保持不变。
friend std::istream &operator>>(std::istream &is, A &a) {
// At least deals with some of the padding problems, but not endianess, etc.
os.read(&a.data, sizeof(a.data));
return os.read((char *)&a.num, sizeof(a.num));
}
Then the rest of the code that uses this doesn't need to change: 然后,使用此代码的其余代码无需更改:
A a;
in >> a; // remains valid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.