0

when appending a file to another weird symbols appear at the end and it's ascii is -1, and if there another way to add a file to the other please share

void AddFile(char old_name[],char old_content[]) {
    ofstream old_file;
    ifstream new_file;
    char new_name[255];
    int len, f_begin, f_end;
    cout << "Enter the file name: ";
    cin.ignore();
    cin.getline(new_name,255,'\n');
    strcat(new_name, ".txt");
    new_file.open(new_name);
    f_begin = new_file.tellg();
    new_file.seekg(0,ios::end);
    f_end = new_file.tellg();
    new_file.seekg(0);
    len = f_end - f_begin;
    char new_content[len+1];
    new_content[len] = '\0';
    for (int i=0; i< len; ++i) {
        new_content[i] = new_file.get();
    }
    new_file.close();
    strcat(old_content,"\n");
    strcat(old_content,new_content);
    old_file.open(old_name);
    cout << old_content;
    old_file << old_content;
    old_file.close();
}

the .tellg() function gives the correct size

  • Possible duplicate of [tellg() function give wrong size of file?](https://stackoverflow.com/questions/22984956/tellg-function-give-wrong-size-of-file) – Andrew Henle Mar 28 '18 at 10:33
  • 1
    Note [this answer](https://stackoverflow.com/a/22986486/4756299): "`tellg` does not report the size of the file, nor the offset from the beginning in bytes. It reports a token value which can later be used to seek to the same place, and nothing more." – Andrew Henle Mar 28 '18 at 10:36
  • I will post a working version. Just for old times sake, it has been 7 years now since I left c++ for c#. – Muhammad Umar Farooq Mar 28 '18 at 12:16

1 Answers1

0

I have written just a snippet of code to help you in the right direction. You can use it or modify as needed.

#include <iostream>
#include <fstream>
using namespace std;


void AddFile(char old_name[], char old_content[]) {
    ofstream old_file;
    ifstream new_file;
    char new_name[255];
    int len, f_begin, f_end;
    cout << "Enter the file name: ";
    /*cin.ignore();
    cin.getline(new_name, 255, '\n');*/
    cin >> new_name;
    strcat(new_name, ".txt");
    new_file.open(new_name);
    old_file.open(old_name, ios::ios_base::app);
    char line[65535];
    while (new_file.getline(line, 65535))
    {
        old_file << endl << line;
    }
    new_file.close();
    old_file.close();

    //verify new data
    new_file.open(old_name);
    while (new_file.getline(line, 65535))
    {
        cout << line << endl;
    }

}

void main()
{
    AddFile("hello.txt", "old data");
}

I might be able to better help if you can share your use case for it.