Add multifile support

This commit is contained in:
Shav Kinderlehrer 2023-04-10 14:36:45 -04:00
parent 1ded2f0f81
commit 6a4a706fc9
3 changed files with 60 additions and 11 deletions

View File

@ -3,4 +3,6 @@
void die(const char *message); void die(const char *message);
char* formatBytes(double *bytes); char* formatBytes(double *bytes);
int intlen(unsigned i);
#endif #endif

View File

@ -24,3 +24,14 @@ char *formatBytes(double *bytes) {
return SIZES[div]; return SIZES[div];
} }
int intlen(unsigned i) {
int l = 1;
while (i > 9) {
l++;
i /= 10;
}
return l;
}

View File

@ -1,23 +1,21 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
#include "lib.h" #include "lib.h"
#define INVERT_T "\x1b[7m" #define INVERT_T "\x1b[7m"
#define UINVERT_T "\x1b[27m" #define UINVERT_T "\x1b[27m"
#define GREY "\x1b[90m"
#define RESET "\x1b[0m"
int main(int argc, char *argv[]) { int run(char *filename) {
if (argc < 2) { FILE *fp = fopen(filename, "r+b");
printf("usage: catclone <FILE>\n");
die("args");
}
FILE *fp = fopen(argv[1], "r+b");
if (fp == NULL) if (fp == NULL)
die("fopen"); die("fopen");
printf("%s%s%s\r\n", INVERT_T, argv[1], UINVERT_T); printf("%s%s%s\r\n", INVERT_T, filename, UINVERT_T);
int bufsize = 4; int bufsize = 4;
char *buf; char *buf;
@ -27,7 +25,8 @@ int main(int argc, char *argv[]) {
die("malloc"); die("malloc");
double fsize = 0; double fsize = 0;
int offset = 0; unsigned offset = 0;
unsigned lc = 0;
char c; char c;
while (fread(&c, sizeof(char), 1, fp) > 0) { while (fread(&c, sizeof(char), 1, fp) > 0) {
if (fsize == bufsize - 1) { if (fsize == bufsize - 1) {
@ -42,17 +41,54 @@ int main(int argc, char *argv[]) {
buf = new_buf; buf = new_buf;
} }
if (c == '\n')
lc++;
buf[offset++] = c; buf[offset++] = c;
fsize++; fsize++;
} }
fclose(fp);
printf("\r\n"); int lcpad = intlen(lc);
lc = 0;
char pc = '\0';
for (int i = 0; i < offset; i++) {
c = buf[i];
if (pc == '\n' || i == 0) {
lc++;
int padlen = lcpad - intlen(lc);
char padding[padlen];
memset(padding, '0', padlen);
printf("%s%s%d:%s ", GREY, padding, lc, RESET);
}
pc = c;
printf("%c", c);
}
char *format = formatBytes(&fsize); char *format = formatBytes(&fsize);
printf("%s%.2f %s%s\r\n", INVERT_T, fsize, format, UINVERT_T); printf("%s%.2f %s%s\r\n", INVERT_T, fsize, format, UINVERT_T);
fclose(fp); return 0;
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("usage: catclone <FILE>\n");
die("args");
}
for (int i = 1; i < argc; i++) {
if (run(argv[i]) != 0)
die("run");
if (i + 1 != argc) {
printf("\r\n");
}
}
return 0; return 0;
} }