【问题标题】:Writing/reading strings as binary into random accessed file将字符串作为二进制写入/读取到随机访问的文件中
【发布时间】:2021-07-22 11:42:19
【问题描述】:

简单问题:我想将固定长度的字符串写入二进制文件(即作为二进制文件),如下面的sn-p所示。

写作“看起来”很好,但从文件中读取不起作用(编译和运行没有崩溃,但没有给出预期的结果)。

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    {
        std::ofstream out {"out.dat", std::ios::binary};

        //all of length 5
        std::string a[] {{"12345"}, {"6789A"}, {"BCDEF"}};

        //write down strings without \0
        out.write(a[0].c_str(), a[0].length());
        out.write(a[1].c_str(), a[1].length());
        out.write(a[2].c_str(), a[2].length());
    }

    {
        std::ifstream in {"out.dat", std::ios::binary};

        std::string s2 {5, '\0'}; //I can store at least 5 chars
        in.seekg(0 + 2 * 5); //try to read string of index 2
        in.read(&s2[0], 5);

        std::cout << s2 << std::endl; //prints "BC", not "BCDEF"  
    }
}

最后一行应该恢复字符串“BCDEF”,但只打印“BC”(g++ 10.2.0)。

由于字符串具有固定长度,并且我将指定数量的字节(字符)写入文件,我应该能够使用seekg 恢复它们(也就是说,我知道它们从哪里开始,并且我可以在此处设置输入位置指示器以读取)。

请注意,这不是this question 的重复,因为我直接写字符(我不需要reinterpret_cast 他们)。

【问题讨论】:

    标签: c++ stdout fstream


    【解决方案1】:

    这使用带有std::initializer_list的构造函数:

    std::string s2 {5, '\0'};
    

    ... 并创建一个包含 2 个字符的字符串,其值为 5 和 0(或任何 \0 值)。

    应该是std::string s2 (5, '\0');

    例子:

    #include <iostream>
    #include <fstream>
    #include <string>
    #include <vector>
    
    int main()
    {
        {
            std::ofstream out {"out.dat", std::ios::binary};
    
            //all of length 5
            std::vector<std::string> a{{"12345"}, {"6789A"}, {"BCDEF"}};
    
            //write down strings without \0
            for(auto& s : a)
                out.write(s.c_str(), s.size());
        }
    
        {
            std::ifstream in {"out.dat", std::ios::binary};
    
            std::string s2(5,'\0'); //I can store at least 5 chars
            in.seekg(0 + 2 * 5); //try to read string of index 2
            in.read(s2.data(), 5);
    
            std::cout << s2 << std::endl; //prints "BC", not "BCDEF"  
        }
    }
    

    `

    【讨论】:

    • 我……惭愧。它是如此简单,与我认为的问题无关......谢谢
    • @R.Absil 不客气!无需感到羞耻——我不得不自己看了两遍。 :-)
    • 谢谢,刚刚做了,还有一些老问题
    猜你喜欢
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    相关资源
    最近更新 更多