我正在尝试在文件中写入 C 结构(以二进制形式写入)并读取它以恢复它。我不知道这是否可能。这是我所拥有的:
头.hh:
#include <iostream>
typedef struct s_test
{
char cmd[5];
std::string str;
}t_test;
主.cpp:
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "head.hh"
int main()
{
t_test test;
int fd = open("test", O_APPEND | O_CREAT | O_TRUNC | O_WRONLY, 0666);
test.cmd[0] = 's';
test.cmd[1] = 'm';
test.cmd[2] = 's';
test.cmd[3] = 'g';
test.str = "hello world";
write(fd, &test, sizeof(t_test));
close(fd);
fd = open("test", O_APPEND | O_CREAT | O_WRONLY, 0666);
t_test test2;
read(fd, &test2, sizeof(t_test));
std::cout << test2.cmd << " " << test2.str << std::endl;
return (0);
}
在输出上我有类似的东西: