用命令行输入目标文件与读取文件名字,xv6 写一个复制文件程序
时间: 2023-05-23 10:03:03 浏览: 49
可以使用以下代码实现:
#include "types.h"
#include "stat.h"
#include "user.h"
#include "fcntl.h"
char buf[1024];
int main(int argc, char *argv[])
{
int fd0, fd1, n;
if (argc != 3) {
printf(1, "Usage: cp file1 file2\n");
exit();
}
if ((fd0 = open(argv[1], O_RDONLY)) < 0) {
printf(1, "cp: cannot open %s\n", argv[1]);
exit();
}
if ((fd1 = open(argv[2], O_CREATE|O_WRONLY)) < 0) {
printf(1, "cp: cannot create %s\n", argv[2]);
exit();
}
while ((n = read(fd0, buf, sizeof(buf))) > 0)
write(fd1, buf, n);
if (n < 0) {
printf(1, "cp: error copying %s\n", argv[1]);
exit();
}
close(fd0);
close(fd1);
exit();
}
相关问题
用命令行输入目标文件与读取文件名字
可以使用以下命令行来输入目标文件路径并读取文件名字:
```
read -p "请输入需读取的文件路径:" filePath && fileName=${filePath##*/}
```
其中,`read` 命令可以让用户在命令行中输入文件路径,`-p` 参数后面跟着的字符串是用来提示用户输入的信息。`&&` 运算符可以在用户成功输入文件路径后再执行下一步操作,即通过 `${filePath##*/}` 来提取文件名字,其中 `##*/` 用于截取字符串中最后一个斜杠后面的部分,即文件名字。
xv6 写一个复制文件程序
可以使用 Unix 的系统调用 open, read 和 write 以及 close 函数来实现文件的复制。以下是复制文件的简单 C 代码示例:
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
return 1;
}
// 打开源文件和目标文件
int src_fd = open(argv[1], O_RDONLY);
int dst_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (src_fd == -1 || dst_fd == -1) {
return 1;
}
// 逐个读取并写入文件内容
char buf[4096];
int n;
while ((n = read(src_fd, buf, sizeof(buf))) > 0) {
if (write(dst_fd, buf, n) != n) {
return 1;
}
}
// 关闭文件
close(src_fd);
close(dst_fd);
return 0;
}
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)