Home >Backend Development >C++ >C program to copy the contents of one file to another file
C File I/O − Create, open, read, write and close files
Files can be used to store large amounts of persistent data. Like many other languages, 'C' provides the following file management functions:
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.
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.
#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; }
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!