Open file + make buffer

This commit is contained in:
Shav Kinderlehrer 2023-04-10 12:51:42 -04:00
parent e2ed5aca4d
commit 1ded2f0f81
3 changed files with 60 additions and 2 deletions

View File

@ -1,4 +1,6 @@
#ifndef LIB_H #ifndef LIB_H
#define LIB_H #define LIB_H
void die(const char *message); void die(const char *message);
char* formatBytes(double *bytes);
#endif #endif

View File

@ -1,7 +1,26 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <sys/ioctl.h>
void die(const char *message) { void die(const char *message) {
perror(message); perror(message);
exit(1); 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];
}

View File

@ -3,18 +3,55 @@
#include "lib.h" #include "lib.h"
#define INVERT_T "\x1b[7m"
#define UINVERT_T "\x1b[27m"
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
if (argc < 2) { if (argc < 2) {
printf("usage: catclone <FILE>\n"); printf("usage: catclone <FILE>\n");
die("args"); die("args");
} }
FILE *fp = fopen(argv[1], "r"); 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);
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); fclose(fp);
return 0; return 0;