C ++ - Как написать и прочитать структуру, которая содержит объект? (писать и читать двоичные файлы)
Я пытаюсь записать структуру C в файл (записать в двоичном виде) и прочитать его, чтобы восстановить его. Я нене знаю, возможно ли это. Вот что у меня есть:
head.hh:
#include
typedef struct s_test
{
char cmd[5];
std::string str;
}t_test;
main.cpp:
#include
#include
#include
#include
#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);
}