Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Everytime I read in by fstream I got 1 extra character at the end

Tags:

c++

fstream

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();
like image 884
Thang Pham Avatar asked May 06 '10 19:05

Thang Pham


1 Answers

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());
like image 186
Jerry Coffin Avatar answered Sep 20 '22 17:09

Jerry Coffin