10

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();
Thang Pham
  • 38,125
  • 75
  • 201
  • 285
  • 3
    Post the code that causes the problem. I woulkd guess that you have opened the file in text (rather than binary) mode and are trying to read it with read(), but who knows. –  May 06 '10 at 19:20
  • Actual code would help. Could this be the newline character('\n')? – Dima May 06 '10 at 19:21
  • 1
    sorry guys, just update my post – Thang Pham May 06 '10 at 19:28

2 Answers2

9

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()) ...

The first two do a read, check whether it failed, and if so exit the loop. The latter two attempt a read, process what's now in the variable, and then exit the loop on the next iteration if the previous attempt failed. On the last iteration, what's in the variable after the failed read will normally be whatever was in it previously, so loops like either of the second two will typically appear to process the last item in the file twice.

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();

This works well for small files, but can slow down substantially for a larger file. In such a case, you typically want to use a loop, reading from one file and writeing to the other. This also has possibilities for subtle errors as well. One way that's been tested and generally work reasonably well looks like this:

    std::ifstream input(in_filename, std::ios::binary);
    std::ofstream output(out_filename, std::ios::binary);

    const size_t buffer_size = 512 * 1024;
    char buffer[buffer_size];

    std::size_t read_size;
    while (input.read(buffer, buffer_size), (read_size = input.gcount()) > 0)
        output.write(buffer, input.gcount());
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
0

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
  • 878
  • 6
  • 5