On 17 Sep, 23:20, Richard Heathfield <r...@see.sig.invalidwrote:
Quote:
>
Here's an appallingly simple encryption program, in C:
>
#include <stdio.h>
#include <stdlib.h>
>
int encrypt(const char *infile, const char *outfile, const char *keyfile)
{
* int rc = 1;
* FILE *in = fopen(infile, "rb");
* if(in != NULL)
* {
* * FILE *out = fopen(outfile, "wb");
* * if(out != NULL)
* * {
* * * FILE *key = fopen(keyfile, "rb");
* * * if(key != NULL)
* * * {
As a matter of style, it might be better to save
multiple levels of indentation by doing something like:
in = fopen ...
out = fopen ...
key = fopen ...
if( in != NULL && out != NULL && key != NULL )
...
But overall easier to use a wrapper function that
prints a proper error message and exits. IMO, it
is laudable to check the return value of fopen,
but incomplete to silently do so. Failures
must be loud. eg:
in = fopen( infile, "rb" );
if( in == NULL ) {
perror( infile );
}
(Standard caveat: not all implementations produce
a useful error message because fopen fails to set
errno.)
Quote:
* * * * int inbyte = 0;
* * * * int keybyte = 0;
* * * * int outbyte = 0;
* * * * rc = 0;
* * * * while((inbyte = getc(in)) != EOF)
* * * * {
* * * * * keybyte = getc(key);
* * * * * if(keybyte == EOF)
* * * * * {
* * * * * * rewind(key);
* * * * * * keybyte = getc(key);
* * * * * }
* * * * * outbyte = inbyte ^ keybyte;
* * * * * putc(outbyte, out);
* * * * }
* * * * fclose(key);
* * * }
* * * fclose(out);
* * }
* * fclose(in);
Hmmm. What happens on IO errors? You need to
check for all errors, Richard! You know that.
It would be much more useful for this function
to take FILE * arguments instead of filenames,
since that would allow the main routine to
pass stdin and stdout as parameters. There's
no need to make the program work only on regular
files, although key needs to be regular for
the rewind to work. (Hmmm, let's test the original
program with a fifo for key and see what happens...
haven't compiled it, but I believe the rewind will
fail and the getc will block.)
Quote:
* }
* return rc;
>
I'm curious to know what 'rc' stands for. I usually
use rc to mean "read count" and write (non-standard)
rc = read( ... ), while returning a variable named
'status'.
--
William Pursell