diff options
author | Shav Kinderlehrer <[email protected]> | 2023-04-10 12:51:42 -0400 |
---|---|---|
committer | Shav Kinderlehrer <[email protected]> | 2023-04-10 12:51:42 -0400 |
commit | 1ded2f0f812b109d14b5f5421305c3d790040dac (patch) | |
tree | 3fd5d386d12d8fe8ae43dc5ea00e4cfdfe0d467c /src | |
parent | e2ed5aca4d72971a9560d60daeb2f1c3ea8acb33 (diff) | |
download | lat-1ded2f0f812b109d14b5f5421305c3d790040dac.tar.gz lat-1ded2f0f812b109d14b5f5421305c3d790040dac.zip |
Open file + make buffer
Diffstat (limited to 'src')
-rw-r--r-- | src/lib.c | 19 | ||||
-rw-r--r-- | src/main.c | 41 |
2 files changed, 58 insertions, 2 deletions
@@ -1,7 +1,26 @@ #include <stdio.h> #include <stdlib.h> +#include <sys/ioctl.h> void die(const char *message) { perror(message); exit(1); } + +char *formatBytes(double *bytes) { + char *SIZES[] = {"bytes", "kB", "MB", "GB"}; + + size_t size = *bytes; + size_t div = 0; + size_t rem = 0; + + while (size >= 1024 && div < (sizeof SIZES / sizeof *SIZES)) { + rem = (size % 1024); + div++; + size /= 1024; + } + + *bytes = (float)size + (float)rem / 1024.0; + + return SIZES[div]; +} @@ -3,18 +3,55 @@ #include "lib.h" +#define INVERT_T "\x1b[7m" +#define UINVERT_T "\x1b[27m" + int main(int argc, char *argv[]) { if (argc < 2) { printf("usage: catclone <FILE>\n"); die("args"); } - FILE *fp = fopen(argv[1], "r"); + FILE *fp = fopen(argv[1], "r+b"); - if (fp == NULL) { + if (fp == NULL) die("fopen"); + + printf("%s%s%s\r\n", INVERT_T, argv[1], UINVERT_T); + + int bufsize = 4; + char *buf; + + buf = malloc(bufsize); + if (buf == NULL) + die("malloc"); + + double fsize = 0; + int offset = 0; + char c; + while (fread(&c, sizeof(char), 1, fp) > 0) { + if (fsize == bufsize - 1) { + bufsize *= 2; + + char *new_buf = realloc(buf, bufsize); + if (buf == NULL) { + free(buf); + die("realloc"); + } + + buf = new_buf; + } + + buf[offset++] = c; + fsize++; } + printf("\r\n"); + + char *format = formatBytes(&fsize); + + printf("%s%.2f %s%s\r\n", INVERT_T, fsize, format, UINVERT_T); + fclose(fp); return 0; |