编写代码: 运行输入./exe [src] [dest] 效果等价于使用cp复制普通文件
时间: 2023-11-25 14:06:35 浏览: 35
以下是一个使用C语言编写的简单程序,实现了将一个文件从源路径复制到目标路径的功能:
```c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#define BUFFER_SIZE 1024
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s [src] [dest]\n", argv[0]);
exit(EXIT_FAILURE);
}
int src_fd = open(argv[1], O_RDONLY);
if (src_fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
int dest_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (dest_fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
char buffer[BUFFER_SIZE];
ssize_t bytes_read;
while ((bytes_read = read(src_fd, buffer, BUFFER_SIZE)) > 0) {
ssize_t bytes_written = write(dest_fd, buffer, bytes_read);
if (bytes_written == -1) {
perror("write");
exit(EXIT_FAILURE);
}
}
if (bytes_read == -1) {
perror("read");
exit(EXIT_FAILURE);
}
if (close(src_fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
if (close(dest_fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
```
这个程序使用了标准的Unix系统调用来打开文件、读取文件内容和写入文件内容。当执行 ./exe [src] [dest] 命令时,程序会尝试打开源文件和目标文件,然后逐个读取源文件中的数据块,并将它们写入目标文件中,直到读取完整个源文件。