//时间:2023年5月2日22点01分
//知识点:文件复制操作
1. 你想要实现什么操作时,出现的bug?
我想要实现文件的复制的时候,出现的bug
2. bug是什么现象?
bug 的现象是:复制得到的文件总是比源文件多几行,而且多的这几行总是最后几行。换句话说,最后几行被多复制了几遍。
3. 出 bug 的源码是什么?
源码为:
/*
* FileTxtCopyTest.cpp
*
* Created on: 2021年5月4日
* Author: hy
* 当前内容主要为测试和使用C++中的文本拷贝(解决二进制文件的读取操作文件复制)
*/
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(int argc, char **argv) {
ifstream is; // 输入流
ofstream os; // 输出流
string isFilePath = "1M.txt"; // 读取的文件位置
string osFilePath = "received_file.txt"; // 写入文件的位置
// 定义一个buffer缓冲区
int bufferSize = 1024;
char* buffer = new char[bufferSize];
// 1. 开始打开文件
is.open(isFilePath, std::ios::binary); // 以二进制方式打开文件
if (is.fail()) {
cout << "打开读取的文件" << isFilePath << "失败!,请检查文件的路径是否存在该文件!" << endl;
return 0;
}
// 2. 开始打开写入文件
os.open(osFilePath, std::ios::binary);
while (is) {
is.read(buffer, bufferSize);
// This is the bug which cause the missing of the origin file.
os.write(buffer, bufferSize);
cout << buffer;
}
delete[] buffer; // 删除buffer
// 3. 顺序方式关闭当前的流
is.close();
os.close();
}
4. bug 在哪里?
bug 在:
os.write(buffer, bufferSize);
改成
os.write(buffer, is.gcount());
就行了。
5. 你怎么知道这么改的?
因为我google 的时候发现了这个源码:
#include <iostream>
#include <fstream>
#include <string>
const static int BUF_SIZE = 4096;
using std::ios_base;
using namespace std;
int main(int argc, char** argv) {
string isFilePath = "1M.txt"; // 读取的文件位置
string osFilePath = "received_file.txt"; // 写入文件的位置
std::ifstream in(isFilePath,
ios_base::in | ios_base::binary); // Use binary mode so we can
std::ofstream out(osFilePath, // handle all kinds of file
ios_base::out | ios_base::binary); // content.
// Make sure the streams opened okay...
char buf[BUF_SIZE];
do {
in.read(&buf[0], BUF_SIZE); // Read at most n bytes into
out.write(&buf[0], in.gcount()); // buf, then write the buf to
cout << buf;
} while (in.gcount() > 0); // the output.
// Check streams for problems...
in.close();
out.close();
}
类比过后才发现的问题。
参考文献:
https://www.oreilly.com/library/view/c-cookbook/0596007612/ch10s08.html
免责声明:
本文素材来源网络,版权归原作者所有。如涉及作品版权问题,请与我联系删除。