chris
chris

Reputation: 11

I can't copy file content to another using fstream in c++(codeblocks). How can I run the file?

I tried to copy from one file to another but I'm getting no output at the end of the program which is running without any error. In the following program firstly I tried create a file(details.txt) with the contents name, rollno, age etc. This part of the code seems to work. The rest of the program doesn't seems to work at all which is to create a second file and copy the content of the file to a char pointer Textfile. Later move the file to a second file(detailscpy.txt). I tried some solutions as directed by my teacher but it doesn't seems to work.

  #include<iostream>
#include<fstream>

using namespace std;
int main()
{
    char name[25];
    char rollno[25];
    int age;
    char nation[20];
    char course[30];
    char* textfile;
    fstream file;
    fstream filecpy;


    cout<<"Enter your name: ";
    cin.getline(name,25);
    cout<<"Enter the course you have enrolled: ";
    cin.getline(course,30);
    cout<<"Enter your rollno: ";
    cin.getline(rollno,20);
    cout<<"Enter your age: ";
    cin>>age;
    cout<<"Enter your nationality: ";
    cin>>nation;


    file.open("details.txt",ios::out);
    if(!file)
    {
      cout<<"Error in creating file.."<<endl;
      return 0;
    }
    cout<<"File created successfully"<<endl;
    file<<name<<endl<<rollno<<endl<<age<<endl<<nation<<endl<<course;

file.close();

    filecpy.open("detailscpy.txt",ios::out);
    if(!filecpy)
    {
        cout<<"error is creating a copy file"<<endl;
        return 0;
    }
    cout<<"Copy file created successfully"<<endl;

   file.open("details.txt", ios::in );

    while(file)
    {


        file>>textfile;
        cout<<textfile;

        filecpy<<textfile<<endl;
    }

        file.close();

    filecpy.close();

    return 0;


}



enter code here

Upvotes: 1

Views: 112

Answers (1)

john
john

Reputation: 87959

You haven't allocated any memory for your pointer char* textfile;. Don't think that will happen automatically. So because you are using an uninitialised pointer your code has undefined behaviour, I'm surprised it didn't crash.

One simple and straightforward way to copy a file is to do it one character at a time.

char ch;
while (file.get(ch)) // read one character
{
    filecpy.put(ch); // and write it out
}

Upvotes: 1

Related Questions