Skip to content

Instantly share code, notes, and snippets.

@aynik
Last active June 8, 2022 09:13
Show Gist options
  • Save aynik/64b2c11a1a4ced40d4966d21109e66cf to your computer and use it in GitHub Desktop.
Save aynik/64b2c11a1a4ced40d4966d21109e66cf to your computer and use it in GitHub Desktop.
interleave / deinterleave
#!/usr/bin/env C -m
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
void deinterleave(const char *out_even_fname, const char *out_odd_fname, int bytes)
{
int c;
FILE *fout_odd, *fout_even;
fout_odd = fopen(out_odd_fname, "wb");
if (!fout_odd)
{
fprintf(stderr, "Couldn't open %s.\n", out_odd_fname);
return;
}
fout_even = fopen(out_even_fname, "wb");
if (!fout_even)
{
fprintf(stderr, "Couldn't open %s.\n", out_even_fname);
fclose(fout_odd);
return;
}
do
{
for (int i = 0; i < bytes; i++)
{
c = fgetc(stdin);
if (feof(stdin))
{
goto done;
}
fputc(c, fout_even);
}
for (int i = 0; i < bytes; i++)
{
c = fgetc(stdin);
if (feof(stdin))
{
goto done;
}
fputc(c, fout_odd);
}
}
while (c != EOF);
done:
fclose(fout_odd);
fclose(fout_even);
}
void usage()
{
printf("Usage: deinterleave\n");
printf(" deinterleave out.even out.odd <bytes per> < in\n");
}
int main(int argc, char **argv)
{
int bytes = 1;
if (argc > 3) {
bytes = atoi(argv[3]);
}
if (argc < 3)
{
usage();
return 0;
}
deinterleave(argv[1], argv[2], bytes);
return 0;
}
#!/usr/bin/env C -m
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
void interleave(const char *in_even_fname, const char *in_odd_fname, int bytes)
{
int c;
FILE *fin_odd, *fin_even;
fin_even = fopen(in_even_fname, "rb");
if (!fin_even)
{
fprintf(stderr, "Couldn't open %s.\n", in_even_fname);
return;
}
fin_odd = fopen(in_odd_fname, "rb");
if (!fin_odd)
{
fprintf(stderr, "Couldn't open %s.\n", in_odd_fname);
fclose(fin_even);
return;
}
do
{
for (int i = 0; i < bytes; i++)
{
c = fgetc(fin_even);
if (c != EOF)
{
fputc(c, stdout);
}
}
for (int i = 0; i < bytes; i++)
{
c = fgetc(fin_odd);
if (c != EOF)
{
fputc(c, stdout);
}
}
} while (c != EOF);
fclose(fin_even);
fclose(fin_odd);
}
void usage()
{
printf("Usage: interleave\n");
printf(" interleave in.even in.odd <bytes per> > out\n");
}
int main(int argc, char **argv)
{
int bytes = 1;
if (argc > 3) {
bytes = atoi(argv[3]);
}
if (argc < 3)
{
usage();
return 0;
}
interleave(argv[1], argv[2], bytes);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment