这通常是由于错误地测试文件结尾而导致的。您通常想做类似的事情:
while (infile>>variable) ...
or:
while (std::getline(infile, whatever)) ...
but NOT:
while (infile.good()) ...
or:
while (!infile.eof()) ...
前两个进行读取,检查是否失败,如果失败则退出循环。后两个尝试读取,处理变量中现在的内容,然后退出循环next如果前一次尝试失败,则进行迭代。在最后一次迭代中,读取失败后变量中的内容通常是之前变量中的内容,因此像后两个循环中的任何一个这样的循环通常会处理文件中的最后一项两次。
要轻松地将一个文件复制到另一个文件,请考虑使用如下内容:
// open the files:
ifstream readfile(inputFile);
ofstream writefile(outputFile);
// do the copy:
writefile << readfile.rdbuf();
这对于小文件来说效果很好,但对于较大的文件来说会大大减慢速度。在这种情况下,您通常需要使用循环,read
从一个文件中获取并且write
向对方。这也有可能出现细微的错误。一种经过测试并且通常工作得相当好的方法如下所示:
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());