//--------------------------------------------------------------------------- //Name: File copying (working with binary files) //Author: Przemyslaw Kudlacik //--------------------------------------------------------------------------- #include //--------------------------------------------------------------------------- int main(int argc, char* argv[]) { //definition of variables FILE * src_filevar,* dst_filevar; //file variables - handles to files in a program char src_fname[256], dst_fname[256]; //file names char buffer[4096]; //buffer int read_count,write_count; long total_read,total_written; //reading file names src_fname[0] = dst_fname[0] = 0; //clear strings - first character = end of string printf("Type source file name: "); scanf("%s",src_fname); printf("Type destination file name: "); scanf("%s",dst_fname); //1. open the files //fopen: first param. = file name, second param. = open mode ("r"-reading, "b"-binary) src_filevar = fopen(src_fname,"rb"); //finish if file not opened - work with file ONLY if fopen succeeded if (src_filevar == NULL) { //file not opened - probably doesn't exist printf("Couldn't open file : '%s'\n",src_fname); fflush(stdin); getc(stdin); //wait for user to press any key return 1; //end program } //open file for reading dst_filevar = fopen(dst_fname,"rb"); //finish if file opened (exists) - don't want to destroy it if (dst_filevar != NULL) { //file opened - exists printf("File '%s' already exists.\n",dst_fname); fflush(stdin); getc(stdin); //wait for user to press any key fclose(src_filevar); //close source file return 2; //end program } //open file for writing dst_filevar = fopen(dst_fname,"wb"); //finish if couldn't open (create) file for writing if (dst_filevar == NULL) { //file not opened - insufficient permissions or disk full printf("Couldn't open file : '%s'\n",dst_fname); fflush(stdin); getc(stdin); //wait for user to press any key fclose(src_filevar); //close source file return 2; //end program } //2. working with files - copying (moving data in a loop from source to destination) printf("Copying '%s' to '%s'. Please wait ...\n",src_fname,dst_fname); total_read = total_written = 0; // work while reading to buffer is possible while ( read_count = fread( (void *)buffer, 1, 4096, src_filevar) ) { // try to write bytes just read to a file write_count = fwrite( (void *)buffer, 1, read_count, dst_filevar); //count statistics total_read = total_read + read_count; total_written = total_written + write_count; //check errors if (read_count != write_count){ printf("COPY ERROR - further writing impossible ..."); break; } } printf("\nCopying finished.\n"); printf("Bytes read : %d\nBytes written : %d\n",total_read,total_written); fflush(stdin); getc(stdin); //wait for user to press any key //3. work with files is finished - close the files fclose(src_filevar); fclose(dst_filevar); return 0; } //---------------------------------------------------------------------------