Linux基础-内建函数

read_write函数读写文件

vi read_write.c 创建一个.c 文件

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

int main(){

        //打开一个已经存在的文件
        int fd = open("english.txt", O_RDONLY);
        if(fd == 1){
                perror("open");
                exit(1);
        }

        //创建一个新文件 -- 写操作
        int fd1 = open("newfile", O_CREAT | O_WRONLY, 0664);
        if(fd == 1){
                perror("open");
                exit(1);
        }
        //read file
        char buf[2048] = {0};
        //返回值-1代表读文件失败 返回值0代表文件读完了 大于0就是读出来的字节数
        int count = read(fd, buf, sizeof(buf));
        if(fd == 1){
                perror("open");
                exit(1);
        }

        while(count){
                //将读出的数据写入另一个文件中
                int ret = write(fd1, buf, count);
                printf("write bytes %d\n", ret);
                //继续读文件
                count = read(fd, buf, sizeof(buf));
        }
        //close file
        close(fd);
        close(fd1);
}

gcc read_write.c -o readwrite 编译.c文件
./readwite
ls -l newfile english.txt 这时候发现两个文件一样大 证明写的没有问题

lseek

功能:
1.获取文件大小
2.移动文件指针
3.文件扩展

用lseek函数做一个文件的扩展

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值