Write a c/c++ program which reads one text file and writes its data to another file. Hint use functions gets() and fputc().
Concept used in this tutorial
Program explanation:
To read and write file in your desire director give path in fopen function e.g
fopen("c:/text.txt","r");
It is recommended to do experiment with code and examine the output of program.
Concept used in this tutorial
- File read
- Write data into text file
- While loop
Program explanation:
- We have two files Input(text.txt) and output(text2.txt) data will be read from input file and write to output file which means that input file will be opened in read mode "r" and output file will be opened in write mode "r".
- We have two if conditions which ensures files are accessible or not.
- Using getc() function in while loop 'ch' is assigned character by character of input file then write into the output file using fuptc() function until it reaches EOF(end of file)
#include <iostream> #include <stdio.h> #include <conio.h> using namespace std; int main() { FILE *input; FILE *output; char ch; input = fopen("text.txt","r"); if(input == NULL){ printf("\n Required File text.txt failed to open "); } else { output = fopen("text2.txt","w"); if(input == NULL){ printf("\n Required File text2.txt failed to open "); } else { //File opened successfully while((ch = getc(input))!= EOF) { fputc(ch, output); } printf("\n Data is Copied "); } } printf("\t\t"); fclose(input ); fclose(output); cout<<"\n\n\n"; return 0; }
To read and write file in your desire director give path in fopen function e.g
fopen("c:/text.txt","r");
It is recommended to do experiment with code and examine the output of program.
But with a minor typing error as shown below
ReplyDeleteoutput = fopen("text2.txt","w");
if(input == NULL){ <<<<------ (output==NULL)
printf("\n Required File text2.txt failed to open ");
How To Write Computer Programs in C and C++ Language With Logic?