c++ 中的 read() 函数类似于 c read()

问题描述 投票:0回答:1

c++中有没有相当于c

read()
的方法?为了说明我的问题,用 C 语言,如果我有:

struct A{  
  char data[4];  
  int num;  
};

...如果我使用:

A* a = malloc (sizeof(struct A));  
read (fd, a, sizeof(struct A));

我可以直接填充我的结构。 C++ 有没有一种方法可以在不使用 C read() 方法的情况下实现此目的?

std::istream
中的方法需要
char*
作为参数,有没有任何方法以
void*
作为参数?

c++ c struct
1个回答
1
投票

最接近的等价物几乎肯定是使用

istream::read
:

struct A {
  char data[4];
  int num;
};

A a;

std::ifstream in("somefile", std::ios::binary);

in.read((char *)&a, sizeof(a));

请注意,这在很多方面与

read
等效,您可能不喜欢它 - 例如,如果您升级编译器,它可能会中断,并且可能只是因为呼吸有点错误而中断。

如果你坚持这样做,你可能至少想隐藏一点丑陋:

struct A { 
   char data[4];
   int num;

   friend std::istream &operator>>(std::istream &is, A &a) { 
       return is.read((char *)a, sizeof(a));
   }
};

然后其他代码将使用普通插入运算符从文件中读取实例:

std::ofstream in("whatever", std::ios::binary);

A a;

in >> a;

这样,当你醒悟过来并更理智地序列化你的对象时,你只需要修改

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));
}

那么使用它的其余代码不需要更改:

A a;
in >> a;  // remains valid
© www.soinside.com 2019 - 2024. All rights reserved.