void fEncode(char* fname, int* key, int nKey)
{
FILE* fp = fopen(fname, "rb+");
short temp;
int i = 0;
while(fread(&temp, 1, 1, fp) == 1)
{
temp = temp ^ *(key+i);
fseek(fp, -1, SEEK_CUR);
fwrite(&temp, 1, 1, fp);
i++;
if(i == nKey)
i = 0;
}
fclose(fp);
}
What I want to achieve is have the user input a file name, and a couple of keys (integer ranging from 0 -> 255). Then I have the first bit XOR with the first key, second bit XOR with second key and so on (When the last key is used, reset to the first one).
The original file will be overwritten with the encoded data. And if the user runs the program again with the same series of keys, the original file will be restored thanks to the nature of XOR.
But, it just won't work, either the loop doesn't end or the encoded data is wrong (The code above has infinite loop).
Any advice is really appreciated. I'm lost on this :(
Logic is incorrect. Your assuming that the new information will fit in the old file's size. This will always cause strange behaviors. Since if you had a string of 2 bytes and then you wrote an integer, which is 4 bytes, you have over wrote the next block of data. The sequential data is corrupted from that point on.
Pattern should be:
Read file into buffer in the program.
Convert the buffer.
Delete the old file
Write the new file from the internal buffer.
Or
Read in one file.
process or convert the read in stuff.
write to a different file.
when finished, delete the old file, rename the new file to the old file's name.
Thanks for your answer. There is one thing I don't understand: Doesn't "rb+" mode treat all character on the file the same size (1 byte)? If so then the new file should have the same size as the original. What am I missing here?
Pointers don't have built in bounds checking, if one goes too far past it's intended end point and overwrites the data to another variable you won't know until you run your app and get corrupted data.
When I read your code, I saw a math equation that would default to an integer for the math and I am not sure if it would be written to the file as a multi byte or would be truncated to a single byte destroying the information you were trying to achieve. If you do not believe me print the results of your math and see where it lands. On thing I also saw was a math equation that would reach beyond the bounds of a 16bit integer pretty quickly. Make sure that your math fits in the character 8-bit data field, which is 0-256.