C++ Rewrite a file but leaving out everything before a word

前端 未结 5 399
天涯浪人
天涯浪人 2020-12-17 01:25

I\'m using Visual C++ Express 2010... and I\'m very new to C++.

I want to read a file then remove everything before the word \"<--START-->\" and rewrite the file

5条回答
  •  天命终不由人
    2020-12-17 02:24

    std::string file_contents = LoadFileAsString("text.txt");
    std::string::size_type offset = file_contents.find("<--START-->");
    std::ofstream("text.txt") << file_contents.c_str() + offset;
    

    With LoadFileAsString defined like this:

    std::string LoadFileAsString(const std::string & fn)
    {
        std::ifstream fin(fn.c_str());
    
        if(!fin)
        {
            std::string what = "LoadFileAsString() : Failed to open file \"";
            what += fn + '\"';
            throw std::runtime_error(what);
        }
    
        std::ostringstream oss;
        oss << fin.rdbuf();
    
        return oss.str();
    }
    

提交回复
热议问题