编写linux下的C程序,完成文件的复制工作。要求通过使用read函数和write函数复制“/etc/passwd”文件到目标文件中,目标文件名在程序运行时从键盘输入
时间: 2024-02-27 09:57:56 浏览: 20
可以使用如下代码在Linux下编写C程序,通过使用`read`函数和`write`函数复制`/etc/passwd`文件到目标文件中,目标文件名在程序运行时从键盘输入:
```c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#define BUFFER_SIZE 4096
int main() {
int source_fd, target_fd;
ssize_t nread;
char buffer[BUFFER_SIZE];
char target_file[100];
printf("请输入目标文件名:");
scanf("%s", target_file);
source_fd = open("/etc/passwd", O_RDONLY);
if (source_fd == -1) {
perror("打开源文件失败");
exit(EXIT_FAILURE);
}
target_fd = open(target_file, O_WRONLY | O_CREAT | O_TRUNC, 0664);
if (target_fd == -1) {
perror("创建目标文件失败");
exit(EXIT_FAILURE);
}
while ((nread = read(source_fd, buffer, BUFFER_SIZE)) > 0) {
if (write(target_fd, buffer, nread) != nread) {
perror("写入目标文件失败");
exit(EXIT_FAILURE);
}
}
if (nread == -1) {
perror("读取源文件失败");
exit(EXIT_FAILURE);
}
if (close(source_fd) == -1) {
perror("关闭源文件失败");
exit(EXIT_FAILURE);
}
if (close(target_fd) == -1) {
perror("关闭目标文件失败");
exit(EXIT_FAILURE);
}
printf("文件复制成功!\n");
return 0;
}
```
在程序中,我们首先通过`open`函数打开源文件`/etc/passwd`,并创建目标文件。接着使用`read`函数从源文件中读取数据,使用`write`函数将数据写入目标文件中。循环直到源文件读取完毕。最后关闭源文件和目标文件即可。注意,在打开目标文件时需要加上`O_CREAT`和`O_TRUNC`标志,表示创建文件和覆盖原有内容。此外,使用`0664`作为文件权限,表示所有者和组可读写,其他用户只能读取。