Linux编程 文件操作 close read write

close函数

函数原型:

#include <unistd.h>
int close(int fd);

参数:

  • fd:要关闭的文件的文件描述符

返回值:

  • 调用成功:返回0;
  • 调用失败:返回-1

功能:关闭一个已经打开的文件。

read函数

函数原型:

#include <unistd.h>
size_t read(int fd, const void *buf, size_t count);

参数:

  • fd:文件描述符
  • buf:缓冲区指针,用于缓存从文件中读取的数据
  • count:要请求读取的字节数

返回值:

  • 调用成功:返回实际读取的字节数;
  • 调用失败:返回-1

功能:从一个打开的额文件中读取文件。

write函数

函数原型:

#include <unistd.h>
size_t write(int fd, const void *buf, size_t count);

参数:

  • fd:文件描述符
  • buf:缓冲区指针,准备写入文件的数据
  • count:要写入文件的字节数

返回值:

  • 调用成功:返回实际写入的字节数
  • 调用失败:返回-1

创建"a.txt"文件,并向文件内写入内容。

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main()
{
        int fd = creat("a.txt", 0644); // 创建一个主用户可读写,组用户可读,其他用户可读的文件,并得到它的文件标识符
        if(fd == -1) {
                printf("创建失败");
                return 0;
        }
        char buf[256] = {"HELLO WORLD!"};

        write(fd, buf, sizeof(buf));
        close(fd);
        return 0;
}

读入"a.txt"文件的内容并输出到屏幕上。

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main()
{
        int fd = open("a.txt", O_RDONLY);
        if(fd == -1) {
                printf("创建失败");
                return 0;
        }
        char buf[256];
        int n = 0;
        while( (n = read(fd, buf, 256)) > 0 )
        {
                write(STDOUT_FILENO, buf, n);
        }
        close(fd);

        return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

golemon.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值