读取文件里的多个相同结构体时如何去除每一个结构体的前两位的标识符
时间: 2023-11-08 19:59:29 浏览: 36
可以使用文件流按照结构体的格式读取文件,然后使用指针将结构体的前两位标识符去掉。
示例代码如下:
```c++
#include <iostream>
#include <fstream>
using namespace std;
struct MyStruct {
int identifier;
int data;
};
int main() {
ifstream infile("data.txt", ios::binary);
if (!infile) {
cout << "Failed to open file!" << endl;
return 1;
}
MyStruct myStruct;
while (infile.read((char*)&myStruct, sizeof(myStruct))) {
// 去除前两位标识符
int* pData = &myStruct.data;
myStruct.identifier = *pData;
*pData = *(pData + 1);
// 输出结构体数据
cout << "Identifier: " << myStruct.identifier << ", Data: " << myStruct.data << endl;
}
infile.close();
return 0;
}
```
假设 data.txt 文件中存储了多个 MyStruct 结构体,每个结构体包含两个 int 类型的成员变量,分别是标识符和数据。以上代码示例从文件中读取每个结构体,并将其前两位标识符去掉,然后输出结构体数据。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)