2 Replies - 24161 Views - Last Post: 26 June 2008 - 11:40 PM Rate Topic: -----

#1 anis_ahmad  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 04-May 08

copy the contents of one file to another

Posted 26 June 2008 - 10:16 PM

I am trying to write a program copying contents of file one to another but it is not working giving error
codes are given below:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<ctype.h>
void main()
{
FILE *fs,*ft;
char ch;
printf("copying contents of one file to another file\n");
fs=fopen("al.cpp","r");
if(fs==NULL)
{
puts("canot open the siurce file\n");
exit(0);
}
ft=fopen("a2.cpp","w");
if(ft==NULL)
puts("\ncannot open target file\n");
fclose(fs);
exit(0);
}
while(1)
{
ch=fgetc(fs);
if(ch==EOF)
break;
else
fputc(ch,ft);
}
fclose(fs);
fclose(ft);
getch();
}


*edit: Please use code tags in the future, thanks! :code:

This post has been edited by Martyr2: 26 June 2008 - 10:20 PM


Is This A Good Question/Topic? 0
  • +

Replies To: copy the contents of one file to another

#2 Martyr2  Icon User is online

  • Programming Theoretician
  • member icon

Reputation: 4187
  • View blog
  • Posts: 11,851
  • Joined: 18-April 07

Re: copy the contents of one file to another

Posted 26 June 2008 - 10:22 PM

Take a look at this thread and you can certain use it to solve your problem. It takes one file and copies it to another. The only difference is that we also number the lines but you can leave that part out if you like.

Copy one file into another

Enjoy!

:)
Was This Post Helpful? 0
  • +
  • -

#3 nitin_c_c++  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 1
  • View blog
  • Posts: 13
  • Joined: 18-June 08

Re: copy the contents of one file to another

Posted 26 June 2008 - 11:40 PM

Hi friend,

Here is the correct listing of the code
#include<stdio.h>  
#include<conio.h>  
#include<stdlib.h>  
#include<ctype.h>  

void main()  
{  
	FILE *fs,*ft;  
	char ch;  
	printf("copying contents of one file to another file\n");  
	fs=fopen("test1.cpp","r");  
	if(fs==NULL)  
	{  
		perror("fopen");
		puts("canot open the source file\n");  
	}  
	
	ft=fopen("test2.cpp","a");  
	if(ft==NULL)  
	{
		puts("\ncannot open target file\n");  
	}
	 		
	while(1)  
	{  
		ch=fgetc(fs);  
		if(ch==EOF)  
			break;  
		else  
			fputc(ch,ft);  
	}  
	
	fclose(fs);  
	fclose(ft);  
	getch();  
}  




In your code there was some compilation problem and also u were closing the source file before copying to destination file.

You can improve your code with proper err handling, I have not done to make it simple.

cheers

This post has been edited by nitin_c_c++: 26 June 2008 - 11:42 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1