File Handling in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • livesinabox
    New Member
    • May 2010
    • 4

    File Handling in C

    Code:
    #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?
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    Your analysis is correct. This program does not copy file1 into file2.

    By the way, line 9 is very dangerous. Terrible things will happen if the user types more than nine characters.

    Comment

    • livesinabox
      New Member
      • May 2010
      • 4

      #3
      Thank you for you're help!
      And yes I was warned against using the gets function.. I changed it to scanf! Thank you!

      Comment

      • mayankarpit
        New Member
        • Jun 2010
        • 13

        #4
        Instead of scanf u should use fgets(). Scanf will not do array boundry check and will terminate reading at first space.

        Comment

        Working...