我修改了一个来自互联网的来源,用于复制文件,以便它可以在运行时从用户那里获取文件路径。
#include <fstream>
#include <memory>
#include <iostream>
#include <string.h>
//C++98 implementation, this function returns true if the copy was successful, false otherwise.
bool copy_file(const char* From, const char* To, std::size_t MaxBufferSize = 1048576)
{
std::ifstream is(From, std::ios_base::binary);
std::ofstream os(To, std::ios_base::binary);
std::pair<char*,std::ptrdiff_t> buffer;
buffer = std::get_temporary_buffer<char>(MaxBufferSize);
//Note that exception() == 0 in both file streams,
//so you will not have a memory leak in case of fail.
while(is.good() and os)
{
is.read(buffer.first, buffer.second);
os.write(buffer.first, is.gcount());
}
std::return_temporary_buffer(buffer.first);
if(os.fail()) return false;
if(is.eof()) return true;
return false;
}
int main()
{
char fileSourcePath[1000];
char fileDestinationPath[1000];
std::cout<<"Enter Path of the source file: ";
std::cin>>fileSourcePath;
std::cout<<"Source Path: "<<fileSourcePath<<std::endl;
std::cout<<"Enter Destination path: ";
std::cin>>fileDestinationPath;
std::cout<<"Destination Path: "<<fileDestinationPath<<std::endl;
bool CopyResult = copy_file(fileSourcePath, fileDestinationPath);
std::boolalpha(std::cout);
std::cout << "Could it copy the file? " << CopyResult << '\n';
}
问题是,当我在copy_file(fileSourcePath, fileDestinationPath);
的源代码中直接输入文件路径程序有效时,但是当我在运行时输入路径时,程序运行并终止给出错误的结果。此外,当我输入c:\ upx时.exe它给出了真实的状态但是dosent复制文件。如何修复它?我做错了什么。