修改这个程序的错误#include <iostream>#include <fstream>#include <string>int main() { std::string source_file_name, target_file_name; std::cout << "请输入源文件名:"; std::cin >> source_file_name; std::cout << "请输入目标文件名:"; std::cin >> target_file_name; std::ifstream source_file(source_file_name, std::ios::binary); std::ofstream target_file(target_file_name, std::ios::binary); if (!source_file || !target_file) { std::cerr << "文件打开失败" << std::endl; return 1; } target_file << source_file.rdbuf(); std::cout << "文件复制成功" << std::endl; return 0;}
时间: 2024-01-20 10:02:31 浏览: 37
这个程序主要是实现文件的复制功能,但是有一个小错误,应该将文件流对象source_file和target_file的打开方式改为 std::ios::in | std::ios::binary 和 std::ios::out | std::ios::binary,这样才能正确的读取和写入二进制文件。另外,建议在使用文件流对象时,对其进行异常判断和关闭操作,以保证程序的稳定性和安全性。修改后的程序如下所示:
```
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::string source_file_name, target_file_name;
std::cout << "请输入源文件名:";
std::cin >> source_file_name;
std::cout << "请输入目标文件名:";
std::cin >> target_file_name;
std::ifstream source_file(source_file_name, std::ios::in | std::ios::binary);
std::ofstream target_file(target_file_name, std::ios::out | std::ios::binary);
if (!source_file || !target_file) {
std::cerr << "文件打开失败" << std::endl;
return 1;
}
target_file << source_file.rdbuf();
if (source_file.bad()) {
std::cerr << "读取文件失败" << std::endl;
source_file.close();
target_file.close();
return 1;
}
source_file.close();
target_file.close();
std::cout << "文件复制成功" << std::endl;
return 0;
}
```