【问题标题】:Read from a file after have written to it with fstream - always empty使用 fstream 写入文件后从文件中读取 - 始终为空
【发布时间】:2021-03-23 07:50:33
【问题描述】:
std::fstream file("filename", std::fstream::in | std::fstream::out | std::fstream::trunc);
    if (file)
    {
        file << "Some text" << std::flush;
        std::string buffer;
        //file >> buffer;
        std::getline(file, buffer);
        std::cout << buffer;
    }

我需要写入文件并从中读取。运行后,我可以看到带有创建文本的文件,但是使用带有两个选项的代码如何读取buffer 它始终为空。我做错了什么?

【问题讨论】:

  • seekg重置读指针。

标签: c++ file c++11 fstream ostream


【解决方案1】:

使用seekg(0) 设置开始位置。当您在文件上写入时,它会将位置移动到末尾,而要读取它,您必须移动到开始。

std::fstream file("filename", std::fstream::in | std::fstream::out | std::fstream::trunc);
if (file)
{
    file << "Some text" << std::flush;
    std::string buffer;
    //file >> buffer;
    file.seekg(0);
    std::getline(file, buffer);
    std::cout << buffer;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多