Copying Files

is this an adaquate way to copy a file?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include fstream

using namespace std;
//totally just wrote this code in this forum text box
// there could be syntax errors
void copy()
{
    ifstream fileIn;
    fileIn.open("old.txt");
    ofstream fileOut;
    fileOut.open("new.txt");
    string temp;
    while(! fileIn.eof())
    {
       fileIn.getline(temp);
       fileOut >> temp;
    }
   fileIn.close();
   fileOut.close();
}
Not really, reading one line at a time. Especially if there is no new line characters used. Nor using the input operator.

Reading till buffer full is a little better, but there could be a fair number of optimization improvements you could do. I'd suggest just use a file manipulation library to handle this for you.

Turbine (20) Jul 15, 2011 at 3:26pm:
---------------------------------------------------------------------------------------

"I'd suggest just use a file manipulation library to handle this for you"



Do you have a library in mind?
It is adequate but if you're not going to modify the stream once it's read, I would use an OS-specific function like CopyFile() for Windows.

Or a system/batch-esque command like system("copy old.txt new.txt")
I have thought about using the system command, but I'm planing in implemented in a win32 gui program, and I don't want the good ole console to be popping up. Which is what I think will happen(could be wrong though).
Then use the windows API CopyFile() function.

Also note that if you want to preserve file properties for the file, you must do a direct copy and not a read-in read-out copy like you first posted.
Ok I tried to do what everyone here said and use the CopyFile function in the windows API, but Im having a little trouble getting it to compile. Here's what I have.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <windows.h>
#include <string>

using namespace std;

class File {
private:
    string filePath;
    string fileName;

public:
    void copy(string);
};

void File::copy(string newPath) {
    string temp = filePath + fileName;
    char* old = temp.c_str;
    temp = newPath + fileName;
    char* newFile = temp.c_str();
    CopyFile(old, newFile, true);
}


It's not compiling because it wants a const char pointer, and wont except a char pointer.
Last edited on
Topic archived. No new replies allowed.