将数组的各个部分放入结构中
Putting parts of array into struct
我正在解析位图标题(只是为了好玩),但我在将数据放入结构中时遇到问题。这是我的代码:
#include <iostream>
#include <fstream>
using namespace std;
struct bmp_header {
char16_t id;
int size;
char16_t reserved1;
char16_t reserved2;
int offset_to_pxl_array;
} bmp_header;
int main(int argc, char *argv[]) {
if (argc < 2) {
cout << "No image file specified." << endl;
return -1;
}
ifstream file(argv[1], ios::in|ios::binary|ios::ate);
streampos f_size = file.tellg();
char *memblock;
if (!file.is_open()) {
cout << "Error reading file." << endl;
return -1;
}
memblock = new char[f_size];
//Read whole file
file.seekg(0, ios::beg);
file.read(memblock, f_size);
file.close();
//Parse header
//HOW TO PUT FIRST 14 BYTES OF memblock INTO bmp_header?
//Output file
for(int x = 0; x < f_size; x++) {
cout << memblock[x];
if (x % 20 == 0)
cout << endl;
}
cout << "End of file." << endl;
delete[] memblock;
return 0;
}
如何将内存块的前 14 个元素放入bmp_header?我一直在尝试在网上搜索一些,但对于这样一个简单的问题,大多数解决方案似乎有点复杂。
最简单的方法是使用 std::ifstream
及其read
成员函数:
std::ifstream in("input.bmp");
bmp_header hdr;
in.read(reinterpret_cast<char *>(&hdr), sizeof(bmp_header));
但有一个警告:编译器将对齐bmp_header
的成员变量。因此,您必须防止这种情况。例如,在gcc
中,您可以通过说__attribute__((packed))
来做到这一点:
struct bmp_header {
char16_t id;
int size;
char16_t reserved1;
char16_t reserved2;
int offset_to_pxl_array;
} __attribute__((packed));
此外,正如@ian-cook在下面的评论中指出的那样,字节序也需要注意。
相关文章:
- 使用cpp中的结构和函数的多个学生条目
- 无法添加多个键以映射将结构作为键
- 结构包含在两个头文件中,这两个文件我都不拥有
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- 从 cin 获取 c++ 中结构中多个枚举的输入
- 为什么这个结构需要 24 个字节
- 是否可以跨多个源文件构建 constexpr 数据结构?
- 在两个.cpp文件之间定义全局类/结构指针
- 如何创建结构的结构结构,等等嵌套多个结构?
- C++结构成员函数定义如果在结构体外部定义,则它们会有所不同
- 不是在结构体内部工作,而是在结构体外部工作的自定义类实例
- 如何在结构体内部实现指针
- 模板函数转换为结构体内部的函数指针
- 可以引用定义在结构体内部的友元操作符吗?
- 容器在结构体内部崩溃
- 从结构体内部调用成员函数指针所指向的函数
- 不能使用SFML在结构体内部构造vector对象
- 将枚举(在结构体内部声明的)值赋给结构体内部相同枚举类型的变量
- 比较if语句中结构体内部的值
- 在结构体内部定义operator()函数