作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
每次我通过 fstream 读入时,最后都会多出 1 个字符,我该如何避免这种情况?
编辑:
ifstream readfile(inputFile);
ofstream writefile(outputFile);
char c;
while(!readfile.eof()){
readfile >> c;
//c = shiftChar(c, RIGHT, shift);
writefile << c;
}
readfile.close();
writefile.close();
最佳答案
这通常是由于文件结尾测试不正确造成的。你通常想做这样的事情:
while (infile>>variable) ...
或:
while (std::getline(infile, whatever)) ...
但不是:
while (infile.good()) ...
或:
while (!infile.eof()) ...
前两个执行读取,检查是否失败,如果失败则退出循环。后两者尝试读取,处理变量中现在的内容,然后如果前一次尝试失败则在下 迭代时退出循环。在最后一次迭代中,读取失败后变量中的内容通常是之前的内容,因此像后两个循环中的任何一个这样的循环通常会出现两次处理文件中的最后一项。
要轻松地将一个文件复制到另一个文件,请考虑使用如下方式:
// open the files:
ifstream readfile(inputFile);
ofstream writefile(outputFile);
// do the copy:
writefile << readfile.rdbuf();
这适用于小文件,但对于较大的文件可能会大大降低速度。在这种情况下,您通常希望使用循环,从一个文件读取
并向另一个文件写入
。这也有可能出现细微的错误。一种经过测试且通常运行良好的方法如下所示:
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());
关于C++:每次我通过fstream读入时,最后都会多出一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2783786/
我是一名优秀的程序员,十分优秀!