open()Linux系统调用函数

这些函数都是用于文件操作的。下面是这些函数的简要说明:

- `open()`:打开文件并返回文件描述符。如果文件不存在,则创建该文件。如果文件已存在,则截断该文件。
- `read()`:从文件描述符中读取数据。
- `write()`:向文件描述符中写入数据。
- `dup2()`:复制一个文件描述符,使其指向同一个文件。
- `dup()`:复制一个文件描述符,使其指向同一个文件。
- `fcntl()`:对打开的文件描述符进行控制操作。

下面是一段使用这些函数的程序,其中包含注释:```c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

int main() {
    int fd = open("test.txt", O_CREAT | O_WRONLY, 0644);
    if (fd == -1) {
        perror("open");
        exit(1);
    }

    int newfd = dup(fd);
    if (newfd == -1) {
        perror("dup");
        exit(1);
    }

    if (dup2(fd, STDOUT_FILENO) == -1) {
        perror("dup2");
        exit(1);
    }

    char buf[] = "Hello World!\n";
    if (write(fd, buf, sizeof(buf)) == -1) {
        perror("write");
        exit(1);
    }

    char buf2[1024];
    if (read(newfd, buf2, sizeof(buf2)) == -1) {
        perror("read");
        exit(1);
    }
    printf("%s", buf2);

    if (close(fd) == -1) {
        perror("close");
        exit(1);
    }
}


```

```cpp

#include <fcntl.h>
#include <unistd.h>

int main(int argc, char* argv[]) {
    // 打开源文件
    int src_fd = open(argv[1], O_RDONLY);
    // 创建目标文件
    int dest_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644);
    // 设置缓冲区大小
    char buf[1024];
    // 读取源文件并写入目标文件
    while (true) {
        // 从源文件读取数据到缓冲区中
        int len = read(src_fd, buf, sizeof(buf));
        if (len == -1) {
            // 读取出错,退出循环
            break;
        } else if (len == 0) {
            // 读取结束,退出循环
            break;
        } else {
            // 将缓冲区中的数据写入目标文件中
            write(dest_fd, buf, len);
        }
    }
    // 关闭文件描述符
    close(src_fd);
    close(dest_fd);
    return 0;
}


```

这个程序的功能是将一个文件复制到另一个文件中。它首先使用 `open()` 函数打开源文件和目标文件,然后使用 `read()` 函数从源文件中读取数据到缓冲区中,再使用 `write()` 函数将缓冲区中的数据写入目标文件中。循环执行这个过程,直到源文件中的数据全部读取完毕。最后,使用 `close()` 函数关闭文件描述符,释放资源。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值