0

我正在尝试在文件中写入 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);
}

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

4

2 回答 2

1

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

实际的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);
}
于 2013-11-14T20:07:07.350 回答
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 会给你一个分段错误。

于 2013-11-14T18:43:01.600 回答