devxlogo

Copying Files with File Streams

Copying Files with File Streams

To copy the contents of one file into another, use the fstream classes. First, open the source file using an ifstream object, then create a target file using ofstream, and finally, read the source into the target using the rdbuf() member function:

 #include int main(){ std::ifstream in ("oldfile.txt"); // open original file std::ofstream out("newfile.txt"); // open target file out << in.rdbuf(); // read original file into target out.close(); // explicit close, unnecessary in this case in.close();// explicit close, unnecessary in this case}

Note that you don't have to call the close() member function because the fstream objects do that automatically when their destructors are invoked. However, you want to call close() if other parts of the program access the files before the fstream objects go out of scope.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist