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

后端 未结 2 1410
我寻月下人不归
我寻月下人不归 2020-12-22 12:53

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:

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-22 13:06

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

    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.

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

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

提交回复
热议问题