Skip to content

Instantly share code, notes, and snippets.

@alex-pat
Created June 19, 2015 18:15
Show Gist options
  • Save alex-pat/a73f6871d78fc91c492a to your computer and use it in GitHub Desktop.
Save alex-pat/a73f6871d78fc91c492a to your computer and use it in GitHub Desktop.
interflow of two sorted files (binary)
FILE* interflow(FILE* f1, FILE* f2)
{
if (!f1 || !f2) return NULL;
FILE *f3 = fopen("3","wb");
fseek(f2,0,2);
fseek(f1,0,2);
fpos_t pos1 = 0, pos2;
pos2 = ftell(f2) - sizeof(int);
int i1, i2, exit1 = 0;
fsetpos(f1,&pos1);
fread(&i1, sizeof(int), 1, f1);
fsetpos(f2, &pos2);
fread(&i2, sizeof(int), 1, f2);
while ( 1 )
{
while ( i1 < i2 )
{
fwrite(&i1, sizeof(int), 1, f3);
if ( feof(f1)) {
exit1 = 1;
break;
}
fread(&i1, sizeof(int), 1, f1);
}
if ( exit1 ) break;
while ( i2 < i1 )
{
fwrite(&i2, sizeof(int), 1, f3);
if ( ftell(f2) == sizeof(int)) break;
fseek(f2, -2*sizeof(int), 1);
fread(&i2, sizeof(int), 1, f2);
}
if ( ftell(f2) == sizeof(int)) break;
}
if ( ftell(f2) == sizeof(int))
while (1)
{
fwrite(&i1, sizeof(int), 1, f3);
if (feof(f1)) return f3;
fread(&i1, sizeof(int), 1, f1);
}
if (exit1)
while (1) {
fwrite(&i2, sizeof(int), 1, f3);
if ( ftell(f2) == sizeof(int)) return f3;
fseek(f2, -2*sizeof(int), 1);
fread(&i2, sizeof(int), 1, f2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment