How to copy text file in C or C++?

后端 未结 6 687
走了就别回头了
走了就别回头了 2020-12-11 06:00

When trying to copy a text file A to another file B, there may have several methods: 1) byte by byte 2) word by word 3) line by line

which one is more efficient?

6条回答
  •  孤街浪徒
    2020-12-11 06:36

    Using buffers:

    #include 
    
    int main()
    {
        std::ifstream    inFile("In.txt");
        std::ofstream    outFile("Out.txt");
    
        outFile << inFile.rdbuf();
    } 
    

    The C++ fstreams are buffered internally. They use an efficient buffer size (despite what people say about the efficiency of stream :-). So just copy one stream buffer to a stream and hey presto the internal magic will do an efficient copy of one stream to the other.

    But learning to do it char by char using std::copy() is so much more fun.

提交回复
热议问题