Created
September 12, 2012 18:38
-
-
Save blucz/3708949 to your computer and use it in GitHub Desktop.
bsort source code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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