如何编写和读取包含对象的结构? (写和读二进制) [英] C++ - How to write and read a structure that contain an object ? (to write and read binary)
问题描述
我正在尝试在文件中写入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);
}
这篇关于如何编写和读取包含对象的结构? (写和读二进制)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!