c ++:ifstream删除文件的内容?

c++: ifstream delete contents of a file?

我正在使用以下功能:

int getline_count()
{
    boost::smatch resultc;
    string sLine;
    int line_add_tmp;
    ifstream infile;
    infile.open("scripts.txt", ios_base::in);
    if (!infile){
        cerr << "scripts.txt could not be opened!" << endl;
    }
    else {
        getline(infile, sLine);
        if (boost::regex_match(sLine, c)) {
            line_add = 2;
        }
        else {
            line_add = 1;
        }

        return line_add;
    infile.close();
    }
}

上述函数的意图是测试文件中的第一行是否包含'// new' 如果为真,则返回2。如果为假,则返回 1。到目前为止效果很好。

让我感到困惑的是,在 运行 之后,文件 scripts.txt 是空的。怎么可能因为

1.) '// new' 行被正确识别,因为我得到 '2' 返回(运行ning 在一个空文件上 returns 1 正如预期的那样)。所以不可能是在打开文件的过程中 scripts.txt 它被空文件覆盖了

2.) ifstream 被设计为只读

我缺少什么?

编辑:

c 的定义是

static const boost::regex
    c("^(\/)(\/)(new|New| new| New)");  // Regexp for line count  

ifstream 永远不应操纵您的文件。您需要在别处寻找您的问题,它不在这段代码中。最好的办法是提供一个 Minimal, Complete, and Verifiable example 来证明您的问题。

但是,您应该检查您的编码,您缺少错误处理和处理编译器警告等基本要素。最有可能的是,如果您的其他代码看起来相同,那就是问题的根源。

就我个人而言,我会这样编写您的函数:

bool first_line_in_file_matches(const std::string& filename, const boost::regex& c)
{
    std::string line;
    std::ifstream infile(filename.c_str());

    if (!infile)
    {
        cerr << filename << " could not be opened!" << endl;
        // TODO: THROW AN EXCEPTION MAYBE? OR RETURN FALSE? EXIT HERE
    }

    return getline(infile, line) && boost::regex_match(line, c);
}

这个函数不会清除文件的内容。所以如果实际上文件被清除了,它是从外部清除到getline_count

为了证明这一点,让我们检查 ifstream 上相对于文件的每个调用的功能:

Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to true). Then (if good), it extracts characters from its associated stream buffer object as if calling its member functions sbumpc or sgetc, and finally destroys the sentry object before returning.

  • ifstream::~ifstream 这是隐式声明的,所以它只是销毁对象,关闭文件;如果这个删除的文件内容没有人能够使用 ifstream

找到文件清除的罪魁祸首的推荐步骤是:

  1. 确保您查看的是正确的文件,并且您的代码之外没有一些进程正在清除文件
  2. 在您的代码中搜索 "scripts.txt" 其他东西必须按名称访问文件并调试它
  3. 禁止写入"scripts.txt",看看能不能找到写入文件失败的代码