【问题标题】:Adding lines to an open file?在打开的文件中添加行?
【发布时间】:2013-06-14 15:49:42
【问题描述】:

我有一个std::ifstream 对象:

std::ifstream file(file_path);

我从中读了几行:

std::getline(file, line);

在流打开时从其他地方向该文件添加行是否合法?例如。即使在 C++ 程序中达到 EOF 后,是否可以通过文本编辑器添加行,并再次调用 getline 以获取新添加的行?标准是怎么说的?

【问题讨论】:

  • 这篇文章似乎相关? stackoverflow.com/questions/15385302/…
  • 打开系统调用可能不会成功。你想做什么,如果你想让一个应用程序写入一个文件,然后另一个同时读取,尝试使用管道,搜索“管道 c++”
  • 这是合法的,但不太可能按照您的意愿行事。不过,你可能会很幸运......
  • 自己试试吧;)

标签: c++ file-io


【解决方案1】:

这是合法的,它应该在大多数合理的操作系统上做你所期望的。请注意,如果您到达 EOF,则需要清除输入流。输出流需要以一种或另一种方式刷新。下面的代码说明了这一点。

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

int main()
{
    const char *f = "f.txt";
    // create an empty file
    std::ofstream os(f);
    os.close();
    std::ifstream is(f);
    for (unsigned i = 1; 3 > i; ++i)
    {
        os.open(f, std::ios_base::out | std::ios_base::app);
        os << "line  " << i << std::endl;
        os.close();
        std::string s;
        is.clear();
        std::getline(is, s);
        std::cerr << s << std::endl;
    }
    os.open(f, std::ios_base::out | std::ios_base::app);
    for (unsigned i = 3; 6 > i; ++i)
    {
        os << "line  " << i << std::endl;
        os.flush();
        std::string s;
        is.clear();
        std::getline(is, s);
        std::cerr << s << std::endl;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多