Create a gist now

Instantly share code, notes, and snippets.

@blucz /bsort.c
Created Sep 12, 2012

What would you like to do?
bsort source code
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
static int recordwidth;
static int comparer(const void *a, const void *b) {
return memcmp(a, b, recordwidth);
}
int main(int argc, char *argv[]) {
if (sizeof(off_t) != 8) {
fprintf(stderr, "off_t is %lu bytes but should be 8\n", sizeof(off_t));
return 1;
}
if (argc != 3) {
fprintf(stderr, "usage: %s <recordwidth> <filename>\n", argv[0]);
return 1;
}
recordwidth = atoi(argv[1]);
int fd = open(argv[2], O_RDWR);
if (fd < 0) { perror("failed to open file"); return 1; }
off_t len = lseek(fd, 0, SEEK_END);
if (len < 0) { perror("failed to seek to end"); return 1; }
off_t start = lseek(fd, 0, SEEK_SET);
if (start != 0) { perror("failed to seek to start"); return 1; }
void *addr = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, fd, 0);
if (addr == MAP_FAILED) {
perror("mmap failed");
return 1;
}
qsort(addr, len / recordwidth, recordwidth, comparer);
munmap(addr, len);
close(fd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment