在C语言中实现类似系统命令`cp`的功能,需要通过系统调用完成文件或目录的复制操作。以下是具体实现步骤和示例代码:
一、核心步骤解析
命令行参数解析
通过`main`函数的`argv`参数获取源路径和目标路径,需进行参数有效性检查。
目录切换与文件操作
- 使用`chdir`函数切换到源目录,或使用`open`函数直接在源路径打开文件。
- 读取源文件内容到缓冲区,使用`read`系统调用。
- 在目标路径创建或打开目标文件,并将缓冲区内容写入目标文件,使用`write`系统调用。
错误处理
检查文件打开、读写操作是否成功,处理文件不存在、权限不足等异常情况。
二、示例代码
```c
include include include include include include // 切换目录函数 int chdir(const char *path) { return chdir(path) == 0 ? 0 : -1; } // 复制文件函数 int copy_file(const char *src, const char *dest) { int src_fd = open(src, O_RDONLY); if (src_fd == -1) { perror("open src"); return -1; } int dest_fd = open(dest, O_WRONLY | O_CREAT | O_TRUNC, 0644); if (dest_fd == -1) { perror("open dest"); close(src_fd); return -1; } char buffer; ssize_t bytes_read; while ((bytes_read = read(src_fd, buffer, sizeof(buffer))) > 0) { if (write(dest_fd, buffer, bytes_read) != bytes_read) { perror("write"); close(src_fd); close(dest_fd); return -1; } } if (bytes_read == -1) { perror("read"); close(src_fd); close(dest_fd); return -1; } close(src_fd); close(dest_fd); return 0; } // 复制目录函数(递归实现) int copy_directory(const char *src, const char *dest) { if (mkdir(dest, 0755) == -1) { perror("mkdir"); return -1; } struct stat statbuf; if (stat(src, &statbuf) == -1) { perror("stat"); return -1; } for (struct dirent *entry = readdir(src); entry != NULL; entry = entry->d_next) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } char src_path; char dest_path; snprintf(src_path, sizeof(src_path), "%s/%s", src, entry->d_name); snprintf(dest_path, sizeof(dest_path), "%s/%s", dest, entry->d_name); if (entry->d_type == DT_DIR) { if (copy_directory(src_path, dest_path) != 0) { return -1; } } else { if (copy_file(src_path, dest_path) != 0) { return -1; } } } return 0; } int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr, "Usage: %s ", argv); return 1; } const char *src = argv; const char *dest = argv; if (strcmp(src, "-r") == 0) { // 复制目录 if (copy_directory(src + 2, dest) != 0) { return 1; } } else { // 复制文件 if (copy_file(src, dest) != 0) { return 1; } } printf("Copy successful! "); return 0; } ``` 三、代码说明 参数处理 - 支持递归复制目录(添加`-r`选项)。 - 检查参数数量是否为2