commit d67dee2b26cca672fe32066e7aa511ee8bc0ccac
parent 5f9b81f1de231521d1922abb7026fc230c52b76f
Author: phoebos <ben@bvnf.space>
Date: Sun, 18 Jul 2021 20:03:15 +0100
base64: read whole file into buffer then encode
Diffstat:
M | base64.c | | | 33 | ++++++++++++++++++++++----------- |
1 file changed, 22 insertions(+), 11 deletions(-)
diff --git a/base64.c b/base64.c
@@ -36,11 +36,7 @@
#include <sys/stat.h>
#include <fcntl.h>
-/* 54 == 76 * 3/4
- * so reading the file 54 bytes at a time will cause
- * the base64 string to be printed out wrapped at 76 chars.
- */
-#define BUF_SIZE 54
+#define BUF_SIZE 2097152
const char tbl_base64[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
@@ -101,6 +97,7 @@ void print_wrapped(char *s, int line_length){
printf("\n");
}
}
+ if (c != 0) printf("\n");
}
int main(int argc, char **argv) {
@@ -137,20 +134,34 @@ int main(int argc, char **argv) {
return 1;
}
}
+
+ /* read the whole file into *buf */
ssize_t bytes;
- unsigned char buf[BUF_SIZE] = {'\0'};
+ size_t used = 0, size = 0;
+ unsigned char *buf = NULL, *temp;
while (1){
- if ((bytes = read(fd, buf, BUF_SIZE)) <= 0 ) {
+ if (used + BUF_SIZE + 1 > size){
+ size = used + BUF_SIZE + 1;
+
+ temp = realloc(buf,size);
+ if (temp == NULL) {
+ /* out of memory */
+ free(buf);
+ return 1;
+ }
+ buf = temp;
+ }
+ if ((bytes = read(fd, buf+used, BUF_SIZE)) <= 0 ) {
if (bytes == 0) break; /* read returns 0 when EOF has been reached */
perror("read");
return 1;
}
+ used += bytes;
- char *output = base64(buf, bytes, dflg);
- printf("%s\n", output);
- //print_wrapped(output, 76);
}
- printf("\n");
+
+ char *output = base64(buf, used, dflg);
+ print_wrapped(output, 76);
if (close(fd) != 0) {
perror("close");