First C++ Program Suggestions

Hello All,

I started teaching myself C about seven months ago and moved up to C++ about two months ago, mostly using the tutorials on this website.

Here is my first stab at a program: a crude, uber-simple copy program that makes a copy of a file the user types and places the copy within the same directory.

It works, but I'm looking for general advice and guidance on what's noob about this (I'm sure there's plenty that is). Any suggestions on practices that I should be steering away from?

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
37
38
39
40
41
42
43
44
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>

using namespace std;

int main()
{
    string filename, copy_filename;
    ifstream orig_file;
    ofstream copy_file;

    cout <<"Enter file to copy: ";
    getline (cin, filename);
    cout <<endl;

    size_t dot = filename.find('.');
    copy_filename.assign(filename);
    copy_filename.insert(dot, "_copy");

    char *source = new char [filename.size()+1];
    strcpy(source, filename.c_str());
    char *dest = new char [copy_filename.size()+1];
    strcpy(dest, copy_filename.c_str());

    orig_file.open(source, ios::binary);
    copy_file.open(dest, ios::binary);
    if (orig_file.is_open() && copy_file.is_open())
    {
        cout <<"Now copying.  Please Wait." <<endl;
        copy_file << orig_file.rdbuf();
        orig_file.close();
        copy_file.close();

        cout <<"File copied successfully.  Press any key to continue." <<endl;
        cin.get();
    }
    else
        cout <<"Cannot copy file." <<endl;

    return 0;
}
Hmmm ... I'll point out everything that sticks out to me.

First, don't forget to delete[] source and dest. And, anyway, you might want to use string for dest and source instead of char*?
Sweet, thanks for the suggestions Whovian! I added the delete[] functions after reading your post. Also, I thought it seemed like unnecessary overhead to go through the conversions from my strings to *chars, too. But I wasn't sure how else to handle it. According to the reference on here, ifstream::open() has to have a *char for its first argument. Is there an cleaner way to extract a *char from a string object than what I coded?
Just pass the result of c_str() directly.
Ah, got it now. Thanks, folks!
Topic archived. No new replies allowed.