Skip to content

Instantly share code, notes, and snippets.

@b4284
Last active January 2, 2019 17:11
Show Gist options
  • Save b4284/ab6b94664667ef49c8c0533f5489f6d1 to your computer and use it in GitHub Desktop.
Save b4284/ab6b94664667ef49c8c0533f5489f6d1 to your computer and use it in GitHub Desktop.
Read books in parallel!
#include <stdio.h>
void clean_eof_array(int eof_i, FILE **farr, int size) {
fclose(farr[eof_i]);
farr[eof_i] = NULL;
for (int i = eof_i + 1; i < size && farr[i] != NULL; i++) {
farr[i - 1] = farr[i];
farr[i] = NULL;
}
}
int main(const int argc, const char **argv) {
FILE *file[10] = { 0 };
for (int i = 1; i < argc; i++) {
file[i - 1] = fopen(argv[i], "r");
}
int size = argc - 1;
while (size > 0) {
for (int i = 0; i < size; i++) {
int c = fgetc(file[i]);
if (feof(file[i])) {
// also decrement i because the file array has been moved.
clean_eof_array(i--, file, size--);
} else {
fputc(c, stdout);
}
}
}
return 0;
}
(use-modules (ice-9 binary-ports))
(define (main args)
(let A ((open-files '())
(filenames (cdr args)))
(if (null? filenames)
(let B ((left '())
(right (reverse open-files)))
(if (null? right)
(if (not (null? left))
(B '() (reverse left)))
(let* ((rhd (car right))
(rtl (cdr right))
(c (get-u8 rhd)))
(if (eof-object? c)
(B left rtl)
(begin
(put-u8 (current-output-port) c)
(B (cons rhd left) rtl))))))
(call-with-input-file (car filenames)
(lambda (port) (A (cons port open-files)
(cdr filenames)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment