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

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

    Well, there are a lot of answers here already, but here's another. It's very short because it's super simple, it's one-pass, perfectly portable, and it doesn't allocate anything on the heap.

    #include 
    #include 
    #include 
    
    void strip_file_beginning( std::istream &in_s, std::ostream &out_s ) {
        std::istreambuf_iterator< char > in( in_s ), in_end;
        std::ostreambuf_iterator< char > out( out_s );
        static char const start_word[] = "<--START-->"; // mind the terminating '\0'
    
        for ( char const *pen = start_word; pen != start_word + sizeof start_word - 1
                                      && in != in_end; ++ in ) {
            if ( * in == * pen ) ++ pen;
            else pen = start_word;
        }
    
        std::copy( in, in_end, out );
    }
    

    http://ideone.com/zh9bd

提交回复
热议问题