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

标签 c++ ifstream

<分区>

我正在使用以下功能:

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'(按预期在空文件上运行返回 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);
}

关于c++:ifstream删除文件的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36152682/

相关文章:

java - 如何通过包装类直接访问类成员方法

使用 fstream fin 从文件读取时 C++ 程序崩溃

c++ - 我无法使用 Code::Blocks 编译任何东西

c++ - 类似于 "if constexpr"但用于类定义

c++ - ifstream 在我的代码中不起作用?

c++ - 读取和打印文件中的值

c++ - 在没有阻塞的情况下在没有数据的管道上打开 ifstream

c++ - 错误重载 >> 运算符从文件读取到类中

c++ - 如何返回智能指针?

C++ - SetUnion 函数的字符串数组参数