在Linux环境下使用C语言实现cp
命令是一个很好的练习,可以帮助你理解文件操作和系统调用。下面是一个简单的示例代码,展示了如何实现基本的cp
功能:
open
, read
, write
, close
等,用于与操作系统内核进行交互。#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
void copy_file(const char *src, const char *dest) {
int src_fd, dest_fd;
char buffer[1024];
ssize_t bytes_read, bytes_written;
// 打开源文件
src_fd = open(src, O_RDONLY);
if (src_fd == -1) {
perror("Error opening source file");
return;
}
// 创建或打开目标文件
dest_fd = open(dest, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
if (dest_fd == -1) {
perror("Error opening destination file");
close(src_fd);
return;
}
// 读取和写入数据
while ((bytes_read = read(src_fd, buffer, sizeof(buffer))) > 0) {
bytes_written = write(dest_fd, buffer, bytes_read);
if (bytes_written != bytes_read) {
perror("Error writing to destination file");
break;
}
}
if (bytes_read == -1) {
perror("Error reading from source file");
}
// 关闭文件
close(src_fd);
close(dest_fd);
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <source> <destination>\n", argv[0]);
return 1;
}
copy_file(argv[1], argv[2]);
return 0;
}
open
失败。确保程序有足够的权限访问这些文件。通过这个简单的实现,你可以深入理解Linux下的文件操作和系统调用,为更复杂的任务打下基础。
领取专属 10元无门槛券
手把手带您无忧上云