Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

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?

like image 372
user297850 Avatar asked Aug 18 '10 12:08

user297850


2 Answers

Using buffers:

#include <fstream>

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.

like image 56
Martin York Avatar answered Oct 28 '22 12:10

Martin York


Just "buffer by buffer", copy files in binary mode and read/write X bytes long parts. I think that fastest solution is to just use copy function of C language itself or system call.

Largest buffer will provide you less HDD find for data operations (faster copying) but more RAM usage.

like image 33
Piotr Müller Avatar answered Oct 28 '22 13:10

Piotr Müller