![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C program to copy the contents of one file to another file?
C Files I/O − Create, Open, Read, Write and Close a File
C File management
A File can be used to store a large volume of persistent data. Like many other languages 'C' provides the following file management functions,
- Creation of a file
- Opening a file
- Reading a file
- Writing to a file
- Closing a file
Following are the most important file management functions available in 'C,'
function | purpose |
---|---|
fopen () | Creating a file or opening an existing file |
fclose () | Closing a file |
fprintf () | Writing a block of data to a file |
fscanf () | Reading a block data from a file |
getc () | Reads a single character from a file |
putc () | Writes a single character to a file |
getw () | Reads an integer from a file |
putw () | Writing an integer to a file |
fseek () | Sets the position of a file pointer to a specified location |
ftell () | Returns the current position of a file pointer |
rewind () | Sets the file pointer at the beginning of a file |
Input: sourcefile = x1.txt targefile = x2.txt Output: File copied successfully.
Explanation
In this program we will copy a file to another file, firstly you will specify a file to copy. We will open the file and then read the file that we wish to copy in "read" mode and 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...
"); exit(EXIT_FAILURE); } target = fopen(target_file, "w"); if (target == NULL) { fclose(source); printf("Press any key to exit...
"); exit(EXIT_FAILURE); } while ((ch = fgetc(source)) != EOF) fputc(ch, target); printf("File copied successfully.
"); fclose(source); fclose(target); return 0; }
Advertisements