How to copy large text files?

I have a problem. I need to find a way to copy from one text file to another FAST!
Let's say for example a file is 50 MB and I need to copy it within about 3 seconds.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream ifstr("pi.txt");
    ofstream ofstr("pi2.txt");
    char x[1000000];
    int y;
    
    if(!ifstr.is_open || !ofstr.is_open)
    {
    cout << "Error!\n";
    system("pause");
    return 0;
}
    while(!ifstr.eof())
    {
    for (y = 0;y < 1000000;y++)
    {
       ifstr >> x[y];
        }
        for (y = 0;y < 1000000;y++)
        {
            ofstr << x[y];
            }}
            
    
    ifstr.close();
    ofstr.close();
    cout << "Done!\n";
    system("pause");
    return 0;
    }

This code just doesn't work! It's too slow!
If anyone has any ideas please help!
Last edited on
You should get unformatted input when copying files
something like ofstr.put ( ifstr.get() ); will copy one character at the time
Thanks man it definitely is faster but if anyone has any other ideas i'll try them
You could copy chunks of the file using write and read
http://www.cplusplus.com/reference/iostream/ostream/write/
You could try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <fstream>

const size_t BUF_SIZE = 8192;

void copy(std::istream& is, std::ostream& os)
{
	size_t len;
	char buf[BUF_SIZE];

	while((len = is.readsome(buf, BUF_SIZE)) > 0)
	{
		os.write(buf, len);
	}
}

int main()
{
	std::ifstream ifs("input.txt");
	std::ofstream ofs("output.txt");

	copy(ifs, ofs);
}
Last edited on
you could also use the WinAPI function CopyFile (): http://msdn.microsoft.com/en-us/library/e1wf9e7w(VS.85).aspx
Thanks you guys are awesome but because I have only recently started working in c++ I decided to use CopyFile() because it's very simple yet very fast
Topic archived. No new replies allowed.