用c语言实现linux文件操作命令mv,【Linux文件操作】使用c语言实现cp命令
时间: 2024-02-11 13:08:29 浏览: 68
好的,针对你的问题,我可以给出以下代码实现:
1. 实现mv命令:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define BUF_SIZE 1024
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: mv <source_file> <destination_file>\n");
exit(EXIT_FAILURE);
}
int src_fd = open(argv[1], O_RDONLY);
if (src_fd == -1) {
printf("Failed to open source file!\n");
exit(EXIT_FAILURE);
}
int dest_fd = open(argv[2], O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (dest_fd == -1) {
printf("Failed to create destination file!\n");
exit(EXIT_FAILURE);
}
char buf[BUF_SIZE];
ssize_t num_read;
while ((num_read = read(src_fd, buf, BUF_SIZE)) > 0) {
if (write(dest_fd, buf, num_read) != num_read) {
printf("Failed to write to destination file!\n");
exit(EXIT_FAILURE);
}
}
if (num_read == -1) {
printf("Failed to read from source file!\n");
exit(EXIT_FAILURE);
}
if (close(src_fd) == -1) {
printf("Failed to close source file!\n");
exit(EXIT_FAILURE);
}
if (close(dest_fd) == -1) {
printf("Failed to close destination file!\n");
exit(EXIT_FAILURE);
}
if (unlink(argv[1]) == -1) {
printf("Failed to remove source file!\n");
exit(EXIT_FAILURE);
}
printf("File moved successfully!\n");
exit(EXIT_SUCCESS);
}
```
2. 实现cp命令:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define BUF_SIZE 1024
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: cp <source_file> <destination_file>\n");
exit(EXIT_FAILURE);
}
int src_fd = open(argv[1], O_RDONLY);
if (src_fd == -1) {
printf("Failed to open source file!\n");
exit(EXIT_FAILURE);
}
int dest_fd = open(argv[2], O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (dest_fd == -1) {
printf("Failed to create destination file!\n");
exit(EXIT_FAILURE);
}
char buf[BUF_SIZE];
ssize_t num_read;
while ((num_read = read(src_fd, buf, BUF_SIZE)) > 0) {
if (write(dest_fd, buf, num_read) != num_read) {
printf("Failed to write to destination file!\n");
exit(EXIT_FAILURE);
}
}
if (num_read == -1) {
printf("Failed to read from source file!\n");
exit(EXIT_FAILURE);
}
if (close(src_fd) == -1) {
printf("Failed to close source file!\n");
exit(EXIT_FAILURE);
}
if (close(dest_fd) == -1) {
printf("Failed to close destination file!\n");
exit(EXIT_FAILURE);
}
printf("File copied successfully!\n");
exit(EXIT_SUCCESS);
}
```
这两个程序使用了Linux系统调用实现文件操作,可以在Linux环境下编译运行。其中mv命令实现了文件的移动,即将源文件移动到目标文件位置并删除源文件;cp命令实现了文件的复制,即将源文件复制到目标文件位置。
阅读全文