Here's a tidied up version that "works" with notes afterwards:
Code:
/* Implement a stream cipher */
#include <stdio.h>
#include <stdlib.h>
/*
This program expects three commandline parameters:
<input file> <output file> <seed value>
*/
int main(int argc, char *argv[]) {
FILE *infp;
FILE *outfp;
char c;
if (argc != 4) {
fputs("Usage: prog <input file> <output file> <seed value>\n", stderr);
return EXIT_FAILURE;
}
infp = fopen(argv[1], "r");
outfp = fopen(argv[2], "w");
/* Test to ensure both files opened successfully */
if (!infp) {
fputs("Input file could not be opened!\n", stderr);
return EXIT_FAILURE;
}
if (!outfp) {
fputs("Output file could not be opened!\n", stderr);
return EXIT_FAILURE;
}
/* The third commandline parameter should be a seed value */
srand(atoi(argv[3]));
while(!feof(infp)) {
c = fgetc(infp);
putc((int)c ^ rand(), outfp);
}
/* close the files */
fclose(infp);
fclose(outfp);
return EXIT_SUCCESS;
}
1) As robatino pointed out, you should probably check to see whether the proper number of arguments have been passed to you. Notice I added this.
2) If your FILE pointers weren't created successfully, you shouldn't let the program continue as it simply wont work. Notice I added "return" to your error handling to halt the program. Furthermore, you were opening the output file using file mode "rw". This is not a valid mode string. Look here for the documentation on fopen() http://www.cplusplus.com/reference/c...dio/fopen.html
3) There's no need to read characters into a buffer like you were doing. If you are going to read each character in one at a time and XOR them individually, just store them in a char, XOR it, and then write it to the output file.
4) You do NOT want to use atoi() to convert the chars from the input files into numbers. Instead, you want to cast them to integers (since they are really just 8-bit integers anyway). These are two completely different things. Here's an example of why:
What you were doing: atoi("8") which equals int 8
What you should do: (int)'8' which equals int 56 (the ASCII encoding of '8')
(Plus, what would happen if you read in an alphabetic character? atoi("a") == ???)
5) The version of the program I wrote "works", but it will fail to do what you expect. I say "works" because it won't segfault, however it will also fail for many input files on most machines. The reason why is because you are opening the files in text mode, but you are performing operations that should really be done in binary mode. For example, on a Windows machine, you will probably read the EOF character somewhere if your input file contains random binary data. In text mode this will cause the EOF flag to be set and your program will terminate without reading in the whole file. To fix this open the files in binary mode and use fread(). In text mode you will also encounter all sorts of other odd errors.
6) I also removed certain unnecessary parts and rearranged things. I apologize but every coder has their own style