2 Replies - 526 Views - Last Post: 28 May 2010 - 06:24 AM Rate Topic: -----

#1 livesinabox  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 28-May 10

File Handling in C

Posted 28 May 2010 - 06:02 AM

#include<stdio.h>
#include<string.h>
main()
{
FILE *f1,*f2;
char str[10];
f1=fopen("file1.dat","w");
printf("Enter contents of file 1 :");
gets(str);
fputs(str,f1);
fclose(f1);
f1=fopen("file1.dat","r");
f2=fopen("file2.dat","w");
fputs(str,f2);

fclose(f1);
fclose(f2);
printf("Contents of copied file is :");
f2=fopen("file2.dat","r");
printf("%s \n",str);
fclose(f2);
}



In the above coding I am supposed to be coping contents of File1.dat to File2.dat.

I am new to this and hence when I was given this coding I tried understanding it. From what I can see, I am accepting a string str from the user and inserting it into File1. And then I am using the same variable "str" to insert content into file2. In this process I am not copying contents of file1 into file2. I am basically inserting the same string into file2. And that doesn't serve the purpose of the question. Am I right?

Is This A Good Question/Topic? 0
  • +

Replies To: File Handling in C

#2 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2246
  • View blog
  • Posts: 9,236
  • Joined: 18-February 07

Re: File Handling in C

Posted 28 May 2010 - 06:23 AM

no you are currently not copying anything.

This code looks like VERY old C -- for one it should be int main() in modern C, secondly using gets() is very bad and should be avoided (fgets() is not as bad though).
Was This Post Helpful? 0
  • +
  • -

#3 Krishs  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 23
  • View blog
  • Posts: 105
  • Joined: 06-April 10

Re: File Handling in C

Posted 28 May 2010 - 06:24 AM

Absolutely right, you are not copying content of first file to second.
I think its basically example of opening writing and closing files than that of copying from one to another .

while for copying file to another you need following steps
1 . open src file in read mode
2 . open dest file in write mode
3 . while there are contents in src file one read that and copy to dest
4 . close both files

e.g
assuming you have src file to copy to dest and you performed first two
steps , here might be you third step
code goes to read bytes from src untill EOF which is indicated by -1
    while(( c = fgetc(src)) != -1)
	{
	  fputc(c,dest);
	}


Possibly there are many ways to do the same but for the time above stated is best suite.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1