Skip to content

Instantly share code, notes, and snippets.

@Sebbyastian
Last active August 10, 2016 06:32
Show Gist options
  • Save Sebbyastian/40be860d95f9df95f319a2f17dc74dde to your computer and use it in GitHub Desktop.
Save Sebbyastian/40be860d95f9df95f319a2f17dc74dde to your computer and use it in GitHub Desktop.
fshuffle.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int fswap(FILE *file, off64_t x, off64_t y, size_t size) {
unsigned char i[size], o[size];
return fseeko64(file, x * size, SEEK_SET) || fread(i, size, 1, file) != 1 ||
fseeko64(file, y * size, SEEK_SET) || fread(o, size, 1, file) != 1 ||
fseeko64(file, y * size, SEEK_SET) || fwrite(i, size, 1, file) != 1 ||
fseeko64(file, x * size, SEEK_SET) || fwrite(o, size, 1, file) != 1 ||
|| fflush(file);
}
int main(int argc, char **argv) {
size_t size;
if (argc <= 1 || sscanf(argv[1], "%zu", &size) != 1) {
puts("Usage: ./app filename");
return EXIT_FAILURE;
}
FILE *file = fopen(argv[2], "rb+");
if (file == NULL) {
puts("Error opening file...");
return EXIT_FAILURE;
}
off64_t position = 0;
for (;;) {
unsigned char entry[size];
if (fread(entry, sizeof entry, 1, file) != 1 || fswap(file, position, position ? rand() % position : 0, sizeof entry)) {
return ferror(file) ? EXIT_FAILURE : 0;
}
fwrite(entry, sizeof entry, 1, stdout);
position++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment