Hi, I made a simple program that copies files. I tried to copy an exe file, but after I tried to run the copied version, it doesn't work properly. Please help:?:

Here's the code for the test file to copy:

#include <iostream>

int main()
{
    std::cout << "Hello!";
    std::cin.get();
    return 0;
}

And the copier:

#include <fstream>
#include <conio.h>
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string OldFile, NewFile, OldContents;
    cout << "Enter file to copy: ";
    cin >> OldFile;
    cout << "\nEnter a new file name: ";
    cin >> NewFile;
    
    ifstream in(OldFile.c_str(),ios::binary);
    if (!in) return 0;
    
    char temp[100000] = {0};
    
    in.read(temp, 100000);
    
    OldContents = temp;
    in.close();
    
    cout << "\nDone reading!";
    ofstream out(NewFile.c_str(), ios::binary);
    
    if (!out) return 0;
    
    out.write(OldContents.c_str(), OldContents.length());
    
    cout << "\nSuccessfully copied file!";
    getch();
    return 0;
}

I can see several possible problem areas.
First, you're reading in to type char, which is a signed type. What will it do with values over +127?

Second, some of those values may be 0. When you do the assignment from the char array to the string, it only copies up until a NULL terminator (value 0) is encountered, so you end up with a truncated string.

If you successfully copied the array contents, what might happen when you output the c_str() result? Probably also halt at a 0 byte.

Consider using type unsigned char, which is better for holding byte values, and accessing the files in binary mode.

This question has already been answered. Start a new discussion instead.