gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:17:39 28 4
gpt4 key购买 nike

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

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

最佳答案

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

实际的 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);
}

关于C++ - 如何写入和读取包含对象的结构? (写入和读取二进制文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19985037/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com