]> diplodocus.org Git - nmh/blobdiff - sbr/base64.c
Another pass at cleaning up (some of) the manpages.
[nmh] / sbr / base64.c
index 6682c3f34f984f974a223c90936320321f6fa101..3a578c21bd2794faeb8bdd570859014788505a08 100644 (file)
@@ -17,6 +17,7 @@ writeBase64aux (FILE *in, FILE *out, int crlf)
 {
     unsigned int cc, n;
     unsigned char inbuf[3];
+    int skipnl = 0;
 
     n = BPERLIN;
     while ((cc = fread (inbuf, sizeof(*inbuf), sizeof(inbuf), in)) > 0) {
@@ -39,7 +40,7 @@ writeBase64aux (FILE *in, FILE *out, int crlf)
            unsigned int i;
 
            for (i = 0; i < cc; i++) {
-               if (inbuf[i] == '\n') {
+               if (inbuf[i] == '\n' && !skipnl) {
                    inbuf[i] = '\r';
                    /*
                     * If it's the last character in the buffer, we can just
@@ -47,7 +48,16 @@ writeBase64aux (FILE *in, FILE *out, int crlf)
                     * everything down and push the last character back.
                     */
                    if (i == cc - 1) {
-                       ungetc('\n', in);
+                       /*
+                        * If we're at the end of the input, there might be
+                        * more room in inbuf; if so, add it there.  Otherwise
+                        * push it back to the input.
+                        */
+                       if (cc < sizeof(inbuf))
+                           inbuf[cc++] = '\n';
+                       else
+                           ungetc('\n', in);
+                       skipnl = 1;
                    } else {
                        /* This only works as long as sizeof(inbuf) == 3 */
                        ungetc(inbuf[cc - 1], in);
@@ -55,6 +65,8 @@ writeBase64aux (FILE *in, FILE *out, int crlf)
                            inbuf[2] = inbuf[1];
                        inbuf[++i] = '\n';
                    }
+               } else {
+                   skipnl = 0;
                }
            }
        }
@@ -71,7 +83,10 @@ writeBase64aux (FILE *in, FILE *out, int crlf)
                outbuf[2] = '=';
        }
 
-       fwrite (outbuf, sizeof(*outbuf), sizeof(outbuf), out);
+       if (fwrite (outbuf, sizeof(*outbuf), sizeof(outbuf), out) <
+            sizeof outbuf) {
+           advise ("writeBase64aux", "fwrite");
+       }
 
        if (cc < sizeof(inbuf)) {
            putc ('\n', out);