繁体   English   中英

如何编写和读取包含对象的结构? (读写二进制文件)

[英]C++ - How to write and read a structure that contain an object ? (to write and read binary)

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

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

在输出上我有类似:Ȟ。

要读取的文件仅以写入方式打开。

实际的std::string对象不能用这种方式编写。 实际对象通常包含几个指针,也许包含一个大小,但不包含实际字符数据。 它需要序列化。

如果您要编写C ++,则应考虑学习使用文件流,而不是此处介绍的内容。

#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);
}

例如,当您将结构转储到二进制文件中时,请参见将其在内存映像中的内容写入磁盘:

class X
{
public:
    int i;
    int j;
};

X lX;
lX.i= 10;
lX.j = 20;

当类lX的对象写入二进制文件时,其外观类似于| 10 | 20 |。 即,当您阅读时,它将正常工作。

但是对于包含任何类似于字符串的指针的类。

class Y
{
public:
    int* pi;
    int j;
};

Y lY;
lY.pi= new int(10); // lets assume this is created at memory location 1001
lY.j = 20;

因此对象lY的pi值为1001(不是10,因为它是一个指针)。 现在,当您将lY写入二进制文件时,它将看起来像| 10001 | 20 |。 当您读回它时,它将构造Y的新对象(例如lY2),其值pi为1001,j为20。现在,pi(是指针)指向什么? 答案是垃圾,那是您在屏幕上看到的东西。 我猜您正在使用Windows来运行它,因为Linux会给您带来分段错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM