| 224行目: | 224行目: | ||
// file_infoを使ってファイル情報にアクセス | // file_infoを使ってファイル情報にアクセス | ||
} | } | ||
</syntaxhighlight> | |||
<br><br> | |||
== 応用例 == | |||
これらの高度な概念は、C++での構造体の強力さと柔軟性を示している。<br> | |||
構造体は、単純なデータグループ化から複雑なシステムプログラミングまで、幅広い用途に活用できる。<br> | |||
<br> | |||
==== データシリアライゼーション ==== | |||
構造体を使用して、データをバイナリ形式でシリアライズすることができる。<br> | |||
<syntaxhighlight lang="c++"> | |||
#include <fstream> | |||
#include <cstring> | |||
struct Record { | |||
int id; | |||
char name[50]; | |||
double salary; | |||
}; | |||
void saveRecord(const Record& r, const std::string& filename) | |||
{ | |||
std::ofstream file(filename, std::ios::binary); | |||
file.write(reinterpret_cast<const char*>(&r), sizeof(Record)); | |||
} | |||
Record loadRecord(const std::string& filename) | |||
{ | |||
Record r; | |||
std::ifstream file(filename, std::ios::binary); | |||
file.read(reinterpret_cast<char*>(&r), sizeof(Record)); | |||
return r; | |||
} | |||
</syntaxhighlight> | |||
<br> | |||
==== メモリマッピングファイル (Linux) ==== | |||
構造体を使用して、メモリマッピングファイルの内容を直接操作することができる。<br> | |||
<syntaxhighlight lang="c++"> | |||
#include <sys/mman.h> | |||
#include <fcntl.h> | |||
#include <unistd.h> | |||
struct SharedData { | |||
int value; | |||
char message[256]; | |||
}; | |||
int main() | |||
{ | |||
int fd = open("shared_memory.bin", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); | |||
ftruncate(fd, sizeof(SharedData)); | |||
SharedData* data = static_cast<SharedData*>(mmap(NULL, sizeof(SharedData), | |||
PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)); | |||
data->value = 42; | |||
strcpy(data->message, "Hello, shared memory!"); | |||
munmap(data, sizeof(SharedData)); | |||
close(fd); | |||
return 0; | |||
} | |||
</syntaxhighlight> | |||
<br> | |||
==== ネットワークプロトコル ==== | |||
構造体を使用して、カスタムネットワークプロトコルを定義することができる。<br> | |||
<syntaxhighlight lang="c++"> | |||
#include <arpa/inet.h> | |||
struct PacketHeader { | |||
uint32_t magic; | |||
uint16_t version; | |||
uint16_t type; | |||
uint32_t length; | |||
void toNetworkOrder() | |||
{ | |||
magic = htonl(magic); | |||
version = htons(version); | |||
type = htons(type); | |||
length = htonl(length); | |||
} | |||
void toHostOrder() | |||
{ | |||
magic = ntohl(magic); | |||
version = ntohs(version); | |||
type = ntohs(type); | |||
length = ntohl(length); | |||
} | |||
}; | |||
</syntaxhighlight> | </syntaxhighlight> | ||
<br><br> | <br><br> | ||