X-Git-Url: https://diplodocus.org/git/nmh/blobdiff_plain/95dfab96c02e8252eafda2b311747578ef0af456..f1920d78123667716f2321d37ce37628603b2700:/sbr/base64.c diff --git a/sbr/base64.c b/sbr/base64.c index 6682c3f3..3a578c21 100644 --- a/sbr/base64.c +++ b/sbr/base64.c @@ -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);