C++ copy file

In this C++ tip, I am going to show you how to copy content of a file to another file.
To copy the content of the source file to the destination file, you read the content of the source file and write it into the destination. In C++, to read a file, you need to use ifstream class. You can use the get() method to read the file character by character or use the getline() method to read the file line by line. To write the content to file, you use ofstream class. These classes are in the fstream library. Writingt text to a file is similar to writing text on the screen. You just change from cout to an object of the ofstream class. Here is the example code to copy hello.txt to hello_copy.txt that are stored in drive D.

#include "iostream"
#include "fstream"
using namespace std;
class fileManager{
public:
   void copyFile(char *sourcefile,char *dscfile){
     ifstream source;
     source.open(sourcefile,ios::in);
     if(source){ // if the source file is opened successfully
        ofstream dsc;
        dsc.open(dscfile,ios::out);
        char data[100];
        while(source.getline(data,100)){
           dsc<<data<<"\n"; // write content to destination file
        }
        dsc.close();

     }
     source.close();
   }
};
int main()
{
   char spath[100]="d:/hello.txt";
   char dpath[100]="d:/hello_copy.txt";
   fileManager fManager;
   fManager.copyFile(spath,dpath);


   return 0;
}


c++ copy file

Posted by: Dara | post date: 05-18-2015 | Subject: C++ Programming Language

write programming tip