Linux 文件的读取与写入

库函数:

#include <unistd.h>

文件的读取:

ssize_t read(int fd, void *buf, size_t count);

返回值:返回值为实际读取到的字节数, 如果返回0, 表示已到达文件尾或是无可读取的数据。若参数count 为0, 则read()不会有作用并返回0  若出错,返回 -1

文件的写入:

ssize_t write(int fd, const void *buf, size_t count);

返回值:成功则write()会返回实际写入的字节数。当有错误发生时则返回-1,错误代码存入errno中。 

fd  :文件描述符(0:与进程的标准输入相结合,1:与进程的标准输出相结合,2:与标准错误向结合)

buf:指向持有被写入数据的缓存区, 或者放入新数据的空缓存区

count: 请求读取或写入的数据大小

代码(code):

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

int main()
{
        int fd;
        char *buf = "Read and write files";
        
        //打开文件 file-3
        fd = open("./file-3",O_RDWR|O_CREAT,0600);
        printf("fd = %d\n",fd);

        //将缓存区 buf 的内容写入文件 file-3 
        int n_write = write(fd,buf,strlen(buf));
        printf("n_write = %d\n",n_write);

        char *readBuf;
        readBuf = (char *)malloc(sizeof(char) * n_write);
        
        //将光标移动到文件开头的位置(read读取的是光标后面的内容)
        lseek(fd,0,SEEK_SET);

        //读取文件的内容到缓存区 readBuf
        int n_read = read(fd,readBuf,n_write);
        printf("readBuf = %s\n",readBuf);
        printf("n_read = %d\n",n_read);
        close(fd);

        return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值