Reputation: 4299
I am new to programming and sometimes even the stuff I write remains mysterious to me. This is my first time asking for help on the internet.
I have a problem here and I haven't been able to solve it for some time now.
This is what I want to do:
Read byte by byte from a file into a vector, modify the bytes and write them back.
This is what happens:
All the encryption stuff seem to work, but somehow after several of these operations a part of the file goes missing.
In the byte modifying process I use char overflows, that means I add some random number to each part of my vector and write it back as a whole.
In my opinion this could be some kind of arithmetic overflow issue I don't know about.
By the way, I use Qt SDK and Windows environment, in case that helps.
Here's the code fragment:
void crypt(string * password,string filename, int sign){
vector<char> stack;
ifstream is;
is.open(filename.c_str());
char c;
for (int i = 0; !is.eof(); i++){
is >> noskipws >> c;
stack.push_back(c);
}
stack.pop_back();
is.close();
int code = 0;
double x;
char method = 0;
int var;
for (int i = 0; i < password->size(); i++)
code += password->at(i);
for (int i = 0; i < (stack.size()); i++){
// some unrelated stuff skipped
if (sign == 1)code += stack[i];
stack[i] += var*method*sign; //<----this might be the cause!
if (sign == -1)code += stack[i];
method = 0;
}
ofstream os;
os.open(filename.c_str());
for (int i = 0; i < stack.size(); i++){
os << noskipws << stack[i];
}
os.flush();
os.close();
}
Sorry for the mess in the code, I kind of wrote it for testing.
Any ideas will be appreciated.
Upvotes: 2
Views: 454
Reputation: 29450
You are opening your files in "text" mode, this can cause problems especially since your output characters will most certainly end up outside the range of printable ASCII characters. This can cause issues as on windows for example, when you try to output the value 0xD (carriage return), the library will convert that into a 0xD followed by 0XA (line feed).
So, try to open your files in binary mode like this:
os.open(filename.c_str(), ios::binary);
Upvotes: 3