C++ - 如何编写和读取包含对象的结构?(写入和读取二进制)

2022-01-09 00:00:00 binary structure c++

我正在尝试在文件中写入 C 结构(以二进制形式写入)并读取它以恢复它.我不知道这是否可能.这是我所拥有的:

I'm trying to write a C structure in a file (to write in binary) and read it to recover it. I don't know if it is possible. Here is what I have :

head.hh:

#include <iostream>

typedef struct s_test
{
  char  cmd[5];
  std::string   str;
}t_test;

main.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);
}

在输出上我有类似的东西:?

And on the output I have something like : ??

推荐答案

要读取的文件以只写方式打开.

The file to read from was being opened as write only.

实际的 std::string 对象不能这样写.实际对象通常包含几个指针,可能还有一个大小,但不包含实际的字符数据.需要序列化.

The actual std::string object can't be written that way. The actual object generally contains a couple of pointers and perhaps a size but not the actual character data. It need to be serialized.

如果您要编写 C++,您应该考虑学习使用文件流,而不是您已经拥有的.

If you're going to be writing C++ you should consider learning to use file streams rather than what you've got here.

#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <io.h>
#include <iostream>
#include <string>
#include <vector>

typedef struct s_test
{
    char cmd[5];
    std::string str;
}t_test;

void Write(int fd, struct s_test* test)
{
    write(fd, test->cmd, sizeof(test->cmd));
    unsigned int sz = test->str.size();
    write(fd, &sz, sizeof(sz));
    write(fd, test->str.c_str(), sz);
}

void Read(int fd, struct s_test* test)
{
    read(fd, test->cmd, sizeof(test->cmd));
    unsigned int sz;
    read(fd, &sz, sizeof(sz));
    std::vector<char> data(sz);
    read(fd, &data[0], sz);
    test->str.assign(data.begin(), data.end());
}

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.cmd[4] = 0;
    test.str = "hello world";
    std::cout << "Before Write: " << test.cmd << " " << test.str << std::endl;

    Write(fd, &test);
    close(fd);

    fd = open("test", O_RDONLY, 0666);
    t_test test2;
    Read(fd, &test2);
    std::cout << "After Read: " << test2.cmd << " " << test2.str << std::endl;
    close(fd);

    return (0);
}

相关文章