【C++】【Bug】记录一个复制文件的时候,debug很长时间的一个bug

文章描述了一个在使用C++进行文件复制时遇到的bug,即复制后的文件比源文件多出几行重复的末尾行。问题出在`os.write(buffer,bufferSize);`这行代码,应该改为`os.write(buffer,is.gcount());`以正确写入读取到的字节数。作者通过对比其他源码和查阅资料找到了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//时间: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

免责声明:

   本文素材来源网络,版权归原作者所有。如涉及作品版权问题,请与我联系删除。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值