1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR_INVOKE 1
#define ERROR_INPUT 2
#define ERROR_IO 3
#define ERROR_MEMORY 4
#define CHUNK_SIZE (size_t)65536
#define TOKEN_EOL '\n'
typedef unsigned char byte_t;
/* outputs line number then line contents */
void prefix_lines(FILE *output, const void *buf, size_t size) {
const byte_t *const init = buf;
const byte_t *start = init,
*eol;
size_t count = 1;
do {
const size_t rem = (size_t)(init + size - start);
eol = memchr(start, TOKEN_EOL, rem);
const size_t len = !eol ? rem : (size_t)(eol + 1 - start);
fprintf(output, "%02zu: %.*s", count++, (int)len, (char *)start);
start += len;
} while (eol);
fputs("\n", output); // last EOL
}
int main(int argc, char *argv[]) {
FILE *input;
int own = 0;
switch (argc) {
case 1:
input = stdin;
break;
case 2:
input = fopen(argv[1], "rb");
if (!input) {
perror("fopen");
return ERROR_INPUT;
}
own = 1;
break;
default:
puts("usage: numl [filename]");
return ERROR_INVOKE;
}
int result = 0;
byte_t *buf = NULL;
size_t size = 0,
chunk = CHUNK_SIZE;
do {
size += chunk;
byte_t *const new = realloc(buf, size);
if (!new) {
perror("realloc");
result = ERROR_MEMORY;
goto end;
}
buf = new;
} while ((chunk = fread(buf + size - CHUNK_SIZE, 1, CHUNK_SIZE, input)) == CHUNK_SIZE);
if (!feof(input) || ferror(input)) {
perror("fread");
result = ERROR_IO;
goto end;
}
size -= CHUNK_SIZE - chunk;
prefix_lines(stdout, buf, size);
end:
free(buf);
if (own)
fclose(input);
return result;
} |
Partager