summaryrefslogtreecommitdiffstats
path: root/stdin.c
diff options
context:
space:
mode:
Diffstat (limited to 'stdin.c')
-rw-r--r--stdin.c65
1 files changed, 65 insertions, 0 deletions
diff --git a/stdin.c b/stdin.c
new file mode 100644
index 0000000..3d2c54a
--- /dev/null
+++ b/stdin.c
@@ -0,0 +1,65 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "main.h"
+
+void stdinMode(char *buffer, int wrap, bool decode, char argv[])
+{
+//wrap encoded lines after COLS character (default 76).
+int size = DEFAULT_SIZE-1;
+
+int i = 0;//position in string
+moreInput: while (i < size)
+ {
+ //yes, reading one byte at a time is slow; but you shouldn't be dumping a file into stdin anyway.
+ if (!(fread(buffer+i, 1, 1*sizeof(unsigned char), stdin))){goto process;}//Goes to process if EOF or if fread fails
+ ++i;//increment i so preiously read char isn't overwritten.
+ }
+//realloc if input could have exceeded buffer
+size += DEFAULT_SIZE;
+buffer = realloc(buffer,size*sizeof(unsigned char));
+if (!buffer){fprintf(stderr,"Realloc Failed!\n"); exit(1);}
+goto moreInput;
+
+process:;
+buffer[i] = '\0';//add null char since function expects it
+
+int result;
+
+if (!decode)
+ {
+ char *output = base64Encode(buffer, i);
+ if (!output){fprintf(stderr, "Malloc Failed!\n"); exit(1);}
+ if (wrap == 0){result = fwrite(output, 1, sizeof(unsigned char)*strlen(output), stdout); goto leave;}//if wrap is set to 0, do no wrapping.
+
+ int charactersLeft = strlen(output);//the total number of characters to print is strlen(output_
+ int x = 0;//position to print from in string so wrap printing works
+
+ while (charactersLeft > wrap)//keep looping until all of the wrap length writes are done
+ {
+ result = fwrite(output+x, 1, sizeof(unsigned char)*wrap, stdout);//write wrap number of characters at a time
+ if (!result){fprintf(stderr, "Fwrite Failed!\n"); exit(1);}//fwrite to stdout should not fail. It's best to just exit if it does.
+ putchar('\n');//add a newline to finish off the wrapped line
+ x += wrap;//increase the printing position to the next position
+ charactersLeft -= wrap;//decrease charactersLeft by how many were printed
+ }
+
+ if (charactersLeft == 0){goto leave;}//if the printed number of characters was perfect, don't print an extra newline
+
+ result = fwrite(output+x, 1, sizeof(unsigned char)*charactersLeft, stdout);//print any remaining characters that are smaller in number than wrap.
+ if (!result){fprintf(stderr, "Fwrite Failed!\n"); exit(1);}//fwrite to stdout should not fail. It's best to just exit if it does.
+ putchar('\n');//add a newline to finish off the wrapped line
+ goto leave;
+ }
+
+if (decode)
+ {
+ int outputLength = base64Decode(buffer, i);
+ if (outputLength == -1){fprintf(stderr,"%s: invalid input\n", argv); free(buffer); exit(1);}//base64 returns -1 if input string was invalid
+ result = fwrite(buffer, 1, sizeof(unsigned char)*outputLength, stdout);
+ goto leave;
+ }
+
+leave: free(buffer);
+exit(0);
+}