练习:将1.txt的内容赋值到2.txt(用O_CREAT)
时间: 2024-05-11 18:17:19 浏览: 8
可以使用以下代码将1.txt的内容赋值到2.txt(如果2.txt不存在,则创建它):
```c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
// 打开1.txt文件
int fd1 = open("1.txt", O_RDONLY);
if (fd1 == -1) {
perror("open 1.txt failed");
exit(1);
}
// 打开2.txt文件,如果不存在则创建它
int fd2 = open("2.txt", O_WRONLY | O_CREAT, 0644);
if (fd2 == -1) {
perror("open 2.txt failed");
exit(1);
}
// 读取1.txt文件的内容,并写入到2.txt文件中
char buf[1024];
ssize_t n;
while ((n = read(fd1, buf, sizeof(buf))) > 0) {
if (write(fd2, buf, n) != n) {
perror("write error");
exit(1);
}
}
// 关闭文件
close(fd1);
close(fd2);
return 0;
}
```
这里使用了系统调用open、read、write和close来操作文件。其中,O_RDONLY表示以只读方式打开文件,O_WRONLY表示以只写方式打开文件,O_CREAT表示如果文件不存在则创建它,0644表示文件权限为644。