C Programming
Computer Programming

C file handling program to copy number of bytes of from a specific offset to another file



Write C file handling program to copy number of bytes of from a specific offset to another file

\* C file handling program to copy number of bytes of from a specific offset to another file *\

# include < stdio.h >
# include < string.h >
# include < stdlib.h >
int   main( )
{

FILE *fp1 ;
FILE *fp2 ;
char ch, filename1[20], filename2[20] ;
int count = 0 ;
int location = 0 ;
int totBytes = 0 ;
unsigned char data[1024] ;

printf("\n Enter the source filename : ") ;
scanf( "%s", filename1 ) ;
fp1 = fopen( filename1, "r" ) ;
if ( fp1 == NULL )
{
      printf(" Cannot open the source file ! \n") ;
      exit(0) ;
}

fseek( fp1, 0, SEEK_END ) ;

// offset of source file to copy
printf("\n Enter offset of source file to copy : ") ;
scanf( "%d", &location ) ;

// number of bytes to copy
printf("\n Enter number of bytes to copy : ") ;
scanf( "%d", &totBytes ) ;

count = ftell(fp1) ;
if( count < (location + totBytes) )
{
      printf("\nGiven number of bytes can not be copy, due to file size.\n" ) ;
      return -1 ;
}

printf("\n Enter the destination filename : ") ;
scanf("%s", filename2) ;
fp2 = fopen(filename2, "w") ;
if (fp2 == NULL)
{
      printf(" Cannot open file ! \n") ;
      exit(0) ;
}

fseek( fp1, location, SEEK_SET ) ;
fread( data, totBytes, 1, fp1 ) ;
fwrite( data, totBytes, 1, fp2 ) ;
data[totBytes] = 0 ;
printf("\n Copied content is : \"%s\"\n", data ) ;
fclose(fp1) ;
fclose(fp2) ;
return 0 ;

}

Output of Program :

Output of C file handling program to copy number of bytes of from a specific offset to another file