c++ - 为什么在 C++ 中尝试使用 fstream 复制文件时遇到数据丢失?
问题描述
我正在使用 C++ 开发一个小项目,该项目是关于复制图像文件的。到目前为止,我似乎无法阻止数据丢失的发生。所有复制的图像都会经历高达 2% 的数据丢失(损坏)。我的代码中是否存在缺陷,或者是我不知道的图像编解码器的问题?另外,有没有更有效的方法来做到这一点?代码在下面。
提前致谢。
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <vector>
#define FILE_SRC "IMAGE1.jpg" // name of file to be copied
#define FILE_DES "IMAGE2.jpg" // name of file clone
using namespace std;
void copy_file()
{
puts("Press Any Key to Begin."); if (cin.ignore()) { ; }
vector <unsigned char> fileData; // data from source file will be temporarily stored in vector
fstream targetFile;
unsigned char targetByte;
// START : copies data from source file and stores in vector
targetFile.open(FILE_SRC, ios::in | ios::binary);
while (targetFile >> targetByte)
{
fileData.push_back(targetByte);
}
targetFile.close();
// END : copies data from source file and stores in vector
puts("File Loaded.");
// START : checks if destination file already exists , if not , create new
targetFile.open(FILE_DES);
if (targetFile.fail())
{
targetFile.close();
targetFile.open(FILE_DES,ios::out);
}
targetFile.close();
// END : checks if destination file already exists , if not , create new
targetFile.open(FILE_DES, ios::app | ios::binary);
// START : writes data from vector to destination file
for (unsigned int i = 0; i < fileData.size(); i++)
{
targetFile << fileData.at(i);
}
targetFile.close();
// END : writes data from vector to destination file
puts("File Copied.");
}
int main()
{
copy_file();
return 0;
}
解决方案
推荐阅读
- ruby - 处理 3 个或更多默认参数 Ruby
- c++ - 在 Netbeans 8.1/8.2 上使用 Netbeans 外部终端时出错
- python - 如何显示使用@dataclass 类装饰器时生成的代码?
- xamarin.ios - 在 InAppBillingPlugin for Xamarin 之后,应用内购买无法连接到 iTunes 商店 ios 12
- alexa - 如何处理 Amazon Alexa 中的域外话语
- javascript - 用于 jquery 的 Python 对象到 json
- ubuntu - LXC,Ubuntu Container - 安装库时出现包问题
- typescript - 自版本 3.1.x 以来缺少类型别名 AAGUID
- python - 'builtin_function_or_method' 和 'int' 的实例之间不支持 Python '<'
- kubernetes - 使用 Kops 的 Kubernetes 将每个 master 放在自己的实例组中是否正确?