Home > Backend Development > C++ > C program to copy the contents of one file to another file

C program to copy the contents of one file to another file

WBOY
Release: 2023-09-23 23:17:02
forward
1362 people have browsed it

C program to copy the contents of one file to another file

C File I/O − Create, open, read, write and close files

C File Management

Files can be used to store large amounts of persistent data. Like many other languages, 'C' provides the following file management functions:

  • Create file
  • Open file
  • Read file
  • To File writing
  • Close file

The following are the most important file management functions in 'C':

Function Purpose
fopen () Create a file or open an existing file
fclose () Close the file
fprintf () Write data blocks to the file
fscanf () Read data blocks from the file
getc () Read a single character from a file
putc () Write a single character to the file
getw () Read an integer from the file
putw () Write an integer to the file
fseek () Sets the file pointer position to the specified position
ftell () Returns the current position of the file pointer
rewind () Set the file pointer to the beginning of the file

Input:
sourcefile = x1.txt
targefile = x2.txt
Output: File copied successfully.
Copy after login

Instructions

In this program, we copy one file to another file, first you will specify the file to be copied. We will open the file and read the file to be copied in "read" mode and the target file in "write" mode.

Example

#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
   char ch;// source_file[20], target_file[20];
   FILE *source, *target;
   char source_file[]="x1.txt";
   char target_file[]="x2.txt";
   source = fopen(source_file, "r");
   if (source == NULL) {
      printf("Press any key to exit...</p><p>");
      exit(EXIT_FAILURE);
   }
   target = fopen(target_file, "w");
   if (target == NULL) {
      fclose(source);
      printf("Press any key to exit...</p><p>");
      exit(EXIT_FAILURE);
   }
   while ((ch = fgetc(source)) != EOF)
      fputc(ch, target);
   printf("File copied successfully.</p><p>");
   fclose(source);
   fclose(target);
   return 0;
}
Copy after login

The above is the detailed content of C program to copy the contents of one file to another file. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template