实现cp命令
时间: 2023-07-05 21:20:22 浏览: 47
`cp` 命令是用于将文件或目录从源位置复制到目标位置的命令,下面是一个简单的实现:
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]) {
if (argc != 3) {
cout << "用法:cp 源文件 目标文件" << endl;
return 1;
}
ifstream infile(argv[1], ios::in | ios::binary);
if (!infile.is_open()) {
cout << "无法打开源文件 " << argv[1] << endl;
return 1;
}
ofstream outfile(argv[2], ios::out | ios::binary);
if (!outfile.is_open()) {
cout << "无法打开目标文件 " << argv[2] << endl;
return 1;
}
char buffer[1024];
streamsize count;
while (!infile.eof()) {
infile.read(buffer, sizeof(buffer));
count = infile.gcount();
outfile.write(buffer, count);
}
infile.close();
outfile.close();
cout << "文件复制成功!" << endl;
return 0;
}
```
这个实现比较简单,主要步骤是打开源文件和目标文件,然后读取源文件中的数据并写入到目标文件中,最后关闭文件流。需要注意的是,为了保证二进制文件的正确性,需要以二进制方式打开文件流。