Thread: very newbie question: how to copy files

  1. #1
    Registered User
    Join Date
    Apr 2002
    Posts
    10

    very newbie question: how to copy files

    hello,

    sorry for a very newbie question:
    how to do the same as "cp -p file1 file2"
    using library functions?

    thanks!!!

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Something like this:
    Code:
    #include <stdio.h>
    
    int main ( void )
    {
      FILE *src, *dst;
      char buffer[BUFSIZ];
      if ( ( src = fopen ( "datain.txt", "r" ) ) != NULL )
        if ( ( dst = fopen ( "dataout.txt", "w" ) ) != NULL )
          while ( fgets ( buffer, sizeof buffer, src ) != NULL )
            fputs ( buffer, dst );
        else
          puts ( "Error" );
      else
        puts ( "Error" );
      return 0;
    }
    -Prelude
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Apr 2002
    Posts
    10

    thanks

    thanks

  4. #4
    Unleashed
    Join Date
    Sep 2001
    Posts
    1,765
    Ah, something I've been looking for. Now Prelude, all I have to do is fix the errors you always try sneaking in, and I am good to go.
    The world is waiting. I must leave you now.

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Here's a slight modification using no variables other than file pointers:

    do fputc( fgetc( fpin ), fpout ); while( !feof( fpin ) );

    This is valid since you have to actually read from the file pointer first to see if you're at the end of the file.

    Quzah.
    Hope is the first step on the road to disappointment.

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    *dissappointed*
    Yet again, someone falls into the trap of not testing for EOF on a read function, but testing for EOF using feof()

    Listen, it's quite simple
    feof() is only true AFTER the first read fails, not after the last read succeeds.

    This means for a 10 byte file, you can read 10 chars and feof() will NOT be true.

    This example writes an extra char to the output file, namely the char cast of EOF itself. It is not a file copier.

    And Prelude's answer probably copes badly with binary files, especially \0 characters.

  7. #7
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    *dissappointed*
    Yet again, someone falls into the trap of not testing for EOF on a read function, but testing for EOF using feof()

    Listen, it's quite simple
    feof() is only true AFTER the first read fails, not after the last read succeeds.
    There is no "trap". I didn't fall into it. The only thing I didn't know, was that you can't simply write EOF. My code worked exactly as I intened it to.

    My only err was in thinking that it would write EOF. After all, 'fputc' takes an integer. As such, EOF is in the valid range, so I believed it would write it, thus correctly terminating the file. That was the only error; not knowing that fputc() wouldn't write EOF.

    Quzah.
    Hope is the first step on the road to disappointment.

  8. #8
    Registered User
    Join Date
    Feb 2002
    Posts
    589
    Originally posted by Salem
    *dissappointed*
    And Prelude's answer probably copes badly with binary files, especially \0 characters.
    So if that isn't a good way to do it. What would the right way be Salem?

  9. #9
    Unleashed
    Join Date
    Sep 2001
    Posts
    1,765
    I second Barjor's question.

    Since Prelude's example copies the contents of the file ( almost like it's copying a page from a book by retyping it ) to another file, then saves it - this doesn't work for binaries files. The file was copied just as if you were to open it with a word processing program then choosing "save as". Would this also mess up compressed files? ( example: zip ).

    -EDIT-

    Actually, I would be shocked to hear that the method I mentioned would work on compressed files.
    Last edited by Shadow; 04-24-2002 at 04:03 PM.
    The world is waiting. I must leave you now.

  10. #10
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    This is a bit more generic, but could stand for some extra error checking:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main ( void )
    {
      size_t len;
      char buf[BUFSIZ];
      FILE *in, *out; 
      if ( ( in = fopen ( "datain.txt", "rb" ) ) != NULL ) {
        if ( ( out = fopen ( "dataout.txt", "wb" ) ) != NULL ) {
          do {
            len = fread ( buf, 1, sizeof buf, in );
            if ( len != 0 )
              fwrite ( buf, 1, len, out );
          } while ( len == sizeof buf );
          fclose ( out );
        }
        else
          puts ( "File open failure: output" );
        fclose ( in );
      }
      else
        puts ( "File open failure: input" );
      return EXIT_SUCCESS;
    }
    -Prelude
    My best code is written with the delete key.

  11. #11
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    As usual, Salem's right. I'll try to post the correct version. Please let me know if there are any errors.
    By the way, I only way I knew he was right was I tested it. I did not know it beforehand.
    Code:
    #include <stdio.h>
    
    int main(void)
    {
       char *src_name = "in.txt";
       char *dst_name = "out.txt";
       FILE *in, *out;
       int c;
    
       if ((in = fopen(src_name,"rb")) == NULL)
       {
          printf("Could not open source file: %s\n",src_name);
          return 1;
       }
    
       if ((out = fopen(dst_name,"wb")) == NULL)
       {
          printf("Could not open destination file: %s\n",dst_name);
          return 1;
       }
    
       while ((c = fgetc(in)) != EOF)
          fputc(c,out);
    
       fclose(in);
       fclose(out);
       return 0;
    }
    Last edited by swoopy; 04-24-2002 at 04:38 PM.

  12. #12
    Has a Masters in B.S.
    Join Date
    Aug 2001
    Posts
    2,263
    here's a full error checking very fast very safe file copy...

    ::edit:: in my opinion i did to much error checking...

    Code:
    #include <stdio.h>
    #include <malloc.h>
    
    int main(void)
    {
        FILE* fin,* fout;
        int filesize;
        char* buf;
    
        if(!(fin = fopen("C:\\filein.xxx","rb")))
        {
            printf("Unable To Open Input File\n");
            return -1;
        }
        if(!(fout = fopen("C:\\fileout.xxx","wb")))
        {
            printf("Unable To Open Output File\n");
            fclose(fin);
            return -1;
        }
    
        if(fseek(fin,0,SEEK_END))
        {
            printf("Seek Error In File\n");
            fclose(fin);
            fclose(fout);  
            return -1;
        }
        
        if(!(filesize = ftell(fin)))
        {
            fclose(fin);
            fclose(fout);  
            return 0; // file is empty just close
        }
        
        if(fseek(fin,0,SEEK_SET))
        {
            printf("Seek Error In InFile\n");
            fclose(fin);
            fclose(fout);  
            return -1;
        }
    
        if(!(buf = (char*) malloc(filesize)))
        {
            printf("Out Of Memory\n");
            fclose(fin);
            fclose(fout);  
            return 0;
        }
    
        if(fread(buf,1,filesize,fin) < filesize)
        {
            free(buf);
            fclose(fin);
            fclose(fout);  
            printf("File Read Error\n");
            return -1;
        }
        if(fwrite(buf,1,filesize,fout) < filesize)
        {
            free(buf);
            fclose(fin);
            fclose(fout);  
            printf("File Write Error\n");
            return -1;
        }
        free(buf);
        fclose(fin);
        fclose(fout);  
        return 0;
    }
    ::edit:: GAH FORGOT TO CLOSE THE FILES!!! i fixed it!!
    ::edit:: this code would be far prettier without so much error checing... and maybe a define for the file closing or something like fcloseall() instead... but then that closes any other file too.
    Last edited by no-one; 04-24-2002 at 05:14 PM.
    ADVISORY: This users posts are rated CP-MA, for Mature Audiences only.

  13. #13
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,490
    the brute force and ignorance method:
    Code:
    #ifdef __win32
    system("copy x.exe y.bas");
    #else
    system("cp x.exe y.bas -f");
    #endif
    since cp is in linux, doesn't it have source code somewhere?

  14. #14
    Unleashed
    Join Date
    Sep 2001
    Posts
    1,765
    *yells* Holy options batman! @ no-one's reply.

    From any of the previous posts,
    Code:
    int CopyFile(char *a, char *b)
    {
        FILE* fin,* fout;
        int filesize;
        char* buf;
    
        if(!(fin = fopen(a,"rb")))
        {
            printf("Unable To Open Input File\n");
            return -1;
        }
        if(!(fout = fopen(b,"wb")))
        {
            printf("Unable To Open Output File\n");
            return -1;
        }
            ETC....
    }
    
    int main()
    {
            CopyFile("c:\\previous\\path\\file.ext", "c:\\new\\path\\file.ext");
            return 0;
    }
    Would this be wrong? Better yet, would it be wrong to put the function CopyFile() into a header file in your compiler's include directory so all your programs may call CopyFile(old spot, new spot)?
    The world is waiting. I must leave you now.

  15. #15
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Or how about?
    Code:
    #include <stdio.h>
    #include <windows.h>
    
    int main(void)
    {
       char src_file[80] = "in.txt";
       char dst_file[80] = "out.txt";
    
       if (CopyFile(src_file,dst_file,TRUE) != 0)
          printf("Copied %s to %s\n",src_file,dst_file);
    return 0;
    }
    Last edited by swoopy; 04-24-2002 at 04:49 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help to copy files in c++
    By Helgso in forum C++ Programming
    Replies: 52
    Last Post: 11-21-2008, 08:50 AM
  2. how to copy binary files using Unix API's
    By rohan_ak1 in forum C Programming
    Replies: 25
    Last Post: 05-07-2008, 09:12 AM
  3. added start menu crashes game
    By avgprogamerjoe in forum Game Programming
    Replies: 6
    Last Post: 08-29-2007, 01:30 PM
  4. Trying to get my App to copy files with wildcards
    By Dwizard in forum Windows Programming
    Replies: 3
    Last Post: 09-30-2005, 05:49 PM
  5. Question About External Files (Beginner)
    By jamez05 in forum C Programming
    Replies: 0
    Last Post: 08-11-2005, 07:05 AM