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

前端 未结 5 407
天涯浪人
天涯浪人 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:16

    You cannot read a file then remove everything before the word "<--START-->" and rewrite the file with the rest, except in memory as answered by Benjamin. Otherwise you need an intermediate file. In all cases you should handle various error conditions. This should do it:

    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main() 
    {   
        if (rename("Text.txt", "Old.txt") == 0)
        {
            try
            {
                ifstream in("Old.txt");
                ofstream out("Text.txt");
                string line;
                while (getline(in, line))
                {
                    size_t pos = line.find("<--START-->");
                    if (pos != string::npos)
                    {
                        string remain = line.substr(pos + 11);
                        if (remain.size())
                            out << remain << endl;
                        break;
                    }
                }
                while (getline(in, line))
                    out << line << endl;
            }
            catch (exception&)
            {
                remove("Text.txt");
                rename("Old.txt", "Text.txt");
                cerr << "Error processing file" << endl;
                return 1;
            }
            remove("Old.txt");
            return 0; 
        }
        cerr << "Error renaming file, access right?" << endl;
        return 2; 
    } 
    

    .

提交回复
热议问题