-2

I want to copy the content of another file to the end of the current file I am using. The code runs, but nothing happens in the file. This is part of the code:

void copyFile(fstream &TEXT, char *Name){
    TEXT.close();
    TEXT.open(Name, ios::in);
    char* character = (char *) malloc(sizeof(char) * 100);
    cin.clear();
    //cin.getline(character, 1000, '\0');
    cout << "Enter File Name: ";
    cin.ignore();
    cin.getline(Name, 100, '\n');;
    TEXT.open(Name, ios::out | ios::app);
    TEXT << " " << character;
    cout << "Done copying..\n";
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

1 Answers1

1

I see a number of problems with this code:

  • allocating character using malloc() instead of new[], and then not reading anything into character before writing it to file, and not deallocating character.

  • opening TEXT with ios::in, not reading anything from it, and then reopening it with ios::out | ios::app without close()'ing it first.

  • reading user input into the memory that Name points to, which may or may not be large enough to hold the user input, or may be pointing at read-only memory, etc.

It is really difficult to figure out what your code is trying to do. But I think you might try something more like this instead:

void copyFile(fstream &TEXT, char *Name) {
    TEXT.close();
    TEXT.open(Name, ios::in);
    ostringstream ss;
    ss << TEXT.rdbuf();
    TEXT.close();
    cout << "Enter File Name: ";
    string otherName;
    getline(cin, otherName);
    TEXT.open(otherName.c_str(), ios::out | ios::app);
    TEXT << " " << ss.str();
    cout << "Done copying..\n";
}

Or, maybe you want something more like this:

void copyFile(fstream &TEXT, char *Name){
    ifstream ifs(Name);
    cout << "Enter File Name: ";
    string otherName;
    getline(cin, otherName);
    TEXT.close();
    TEXT.open(otherName.c_str(), ios::out | ios::app);
    TEXT << " " << ifs.rdbuf();
    cout << "Done copying..\n";
}

Or, maybe simply this:

void copyFile(fstream &TEXT, char *Name) {
    ifstream ifs(Name);
    TEXT << " " << ifs.rdbuf();
    cout << "Done copying..\n";
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770