Open In App

C++ program to append content of one text file to another

Last Updated : 23 Nov, 2022
Comments
Improve
Suggest changes
4 Likes
Like
Report

Given source and destination text files. Append the content from the source file to the destination file and then display the content of the destination file.
Example :

Input : file.txt : "geeks", file2.txt : "geeks for"
Output: file2.txt : "geeks for geeks"

Method 1:
Approach:

  1. Open file.txt in inputstream and file2.txt in outputstream with the append option, so that the previous content of the file are not deleted.
  2. Check if there’s an error in opening or locating a file. If yes, then throw an error message.
  3. If both files are found, then write content from the source file to the destination file.
  4. Display the content of the destination file.

Below is the implementation of the above approach:


Output
file not found

Method 2: We can do the same using different functions mentioned below:

  • fopen(): Returns a pointer to the object that controls the opened file stream
  • fprintf(): Writes the string pointed by format to the stream
  • fclose(): Closes the file associated with the stream and disassociates it.
  • fgetc(): Returns the character currently pointed by the internal file position indicator of the specified stream

Approach:

  1. Open source file in read mode and destination file in append mode using fopen()
  2. check if they exist
  3. Iterate every character of the source file using fgetc() and print it to the destination file using fprintf() with while loop
  4. Close both files using fclose()
  5. Open destination file in read mode
  6. print it
  7. close it

Below is the implementation of the above approach:


Output
file not found

Article Tags :
Practice Tags :

Similar Reads