将数组的一部分放入结构中
Putting parts of array into struct
我正在解析位图 header(只是为了好玩),但我无法将数据放入结构中。这是我的代码:
#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;
}
如何将memblock的前14个元素放入bmp_header?我一直在尝试在网上搜索一下,但对于这样一个简单的问题,大多数解决方案似乎都有些复杂。
最简单的方法是使用 std::ifstream
及其 read
成员函数:
std::ifstream in("input.bmp");
bmp_header hdr;
in.read(reinterpret_cast<char *>(&hdr), sizeof(bmp_header));
不过有一个警告:编译器将 align 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 在下面的评论中所指出的,字节顺序也需要注意。
我正在解析位图 header(只是为了好玩),但我无法将数据放入结构中。这是我的代码:
#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;
}
如何将memblock的前14个元素放入bmp_header?我一直在尝试在网上搜索一下,但对于这样一个简单的问题,大多数解决方案似乎都有些复杂。
最简单的方法是使用 std::ifstream
及其 read
成员函数:
std::ifstream in("input.bmp");
bmp_header hdr;
in.read(reinterpret_cast<char *>(&hdr), sizeof(bmp_header));
不过有一个警告:编译器将 align 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 在下面的评论中所指出的,字节顺序也需要注意。