Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

copying file in one chunk 3

Status
Not open for further replies.

sedj

Programmer
Aug 6, 2002
5,610
Hi, how do I go about copying a file in C in one large chunk. At the moment I am doing :

Code:
        FILE* fileIn = fopen("in.txt", "r");
        FILE* fileOut = fopen("out.txt", "w");

        int c;
        while ((c = getc(fileIn)) != EOF) {
                putc(c, fileOut);
        }
        fclose(fileIn);
        fclose(fileOut);

Thanks for any help.

--------------------------------------------------
Free Database Connection Pooling Software
 
Maybe something like this?
Code:
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
   FILE* fileIn  = fopen("in.txt",  "rb");
   FILE* fileOut = fopen("out.txt", "wb");
   if ( fileIn && fileOut ) {
      if ( fseek(fileIn, 0, SEEK_END) == 0 ) {
         long offset = ftell(fileIn);
         if ( offset != -1L ) {
            char *buffer = malloc(offset);
            if ( buffer ) {
               size_t bytes;
               rewind(fileIn);
               bytes = fread (buffer, 1, offset, fileIn);
               fwrite(buffer, 1, bytes,  fileOut);
               fclose(fileIn);
               fclose(fileOut);
               free(buffer);
            }
         }
      }
   }
   return 0;
}
 
Thanks very much, that was just the ticket.

--------------------------------------------------
Free Database Connection Pooling Software
 
Code:
char buff[BUFSIZ];
size_t n;

while ( (n=fread(buff,1,BUFSIZ,fileIn)) != 0 ) {
  fwrite(buff,1,n,fileOut);
}
if ( !feof(fileIn) ) {
  // copy failed
}

Saves all that messing about with allocated memory - like what happens when the file is so large that it exceeds say the physical amount of RAM you have.
1. It's likely to start swapping (read from file, write to swap, read from swap, write to file) (UGH!!).
2. the malloc might actually fail.

--
 
Salem,
some additions (for thoroughness;):
Code:
...
size_t m;
while ((n=fread(buff,1,BUFSIZ,fileIn)) != 0 
     &&(m=fwrite(buff,1,n,fileOut)) == n)
  ...
if ( !feof(fileIn) || m != n) /* or write errors... */
I think it's better to allocate true large buffers in the heap...
 
Thanks for the other suggestions too !

--------------------------------------------------
Free Database Connection Pooling Software
 
In the end I've gone with Salem's solution, as it seems to be the quickest.

Thanks for the help.

--------------------------------------------------
Free Database Connection Pooling Software
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top