tags:

views:

185

answers:

2

Everytime I read in by fstream I got 1 extra character at the end, How can I avoid this?

EDIT:

ifstream readfile(inputFile);
ofstream writefile(outputFile);
char c;
while(!readfile.eof()){
      readfile >> c;
      //c = shiftChar(c, RIGHT, shift);
      writefile << c;
}
readfile.close();
writefile.close();
+3  A: 

This typically results from testing for the end of file incorrectly. You normally want to do something like:

while (infile>>variable) ...

or:

while (std::getline(infile, whatever)) ...

but NOT:

while (infile.good()) ...

or:

while (!infile.eof()) ...

Edit: The first two do a read, check whether it failed, and if so exit the loop. The latter two attempt a read, process what was "read", and then exit the loop on the next iteration if the previous attempt failed.

Edit2: to copy one file to another easily, consider using something like this:

// open the files:
ifstream readfile(inputFile);
ofstream writefile(outputFile);

// do the copy:
writefile << readfile.rdbuf();
Jerry Coffin
Can you explain why the last 2 are wrong?
Seth Illgard
awesome !! that solve the problem. U might elaborate on why `.eof()` is not a good idea?
Harry Pham
See his first edit.
Matteo Italia
A: 

Based on the code, it appears what you're trying to do is copy the contents of one file to another?

If so, I'd try something like this:

ifstream fin(inputFile, ios::binary);

fin.seekg(0, ios::end);
long fileSize = fin.tellg();
fin.seekg(0, ios::beg);

char *pBuff = new char[fileSize];
fin.read(pBuff, fileSize);
fin.close();

ofstream fout(outputFile, ios::binary)
fout.write(pBuff, fileSize);
fout.close;
delete [] pBuff;
Daniel