Skip to content

Instantly share code, notes, and snippets.

@yurial
Created June 30, 2011 17:22
Show Gist options
  • Save yurial/1056700 to your computer and use it in GitHub Desktop.
Save yurial/1056700 to your computer and use it in GitHub Desktop.
swap the file bytes
#include <stdio.h>
#define BUFF_SIZE (4*1024)
void swap(char* buff, size_t count)
{
char* begin = buff;
char* end = buff + count - 1;
while ( begin < end )
{
*begin += *end;
*end = *begin - *end;
*begin = *begin - *end;
++begin;
--end;
}
}
int main(int argc, char* argv[])
{
if ( argc != 3 )
{
fprintf( stderr, "usage: %s <infile> <outfile>\n", argv[0] );
return -1;
}
FILE* infile = fopen( argv[1], "rb" );
if ( NULL == infile )
{
fprintf( stderr, "can't open input file\n" );
return -2;
}
FILE* outfile = fopen( argv[2], "wb+" );
if ( NULL == outfile )
{
fprintf( stderr, "can't create output file\n" );
return -3;
}
fseek( infile, 0, SEEK_END );
int size = ftell( infile );
int smallblocks = size % BUFF_SIZE;
int bigblocks = size / BUFF_SIZE - (0 == smallblocks);
char buff[BUFF_SIZE];
do
{
fseek( infile, bigblocks * BUFF_SIZE, SEEK_SET );
size_t nread = fread( buff, 1, BUFF_SIZE, infile );
swap( buff, nread );
size_t nwrite = fwrite( buff, nread, 1, outfile );
if ( 1 != nwrite )
{
fprintf( stderr, "can't write to file, disk is full?\n" );
return -4;
}
}
while ( bigblocks-- );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment