簡體   English   中英

c ++中的read()函數類似於c read()

[英]read() function in c++ similar to c read()

有什么等效於c ++中的c read()方法嗎? 為了說明我的問題,如果我有C,請使用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*作為參數的方法?

最接近的等效方法幾乎可以肯定是使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM