2-28练习

文件IO中read的应用以及利用read和write重写复制、粘贴功能

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


int main(int argc, const char *argv[])
{
    //r、r+、w、w+、a、a+
    //r:O_RDONLY
    //r+:O_RDWR
    //W:O_WRONLY | O_TRUNC | O_CREAT
    //W+:O_RDWR | O_TRUNC | O_CREAT
    //a:O_APPEND | O_CREAT
    //a+:O_RDONLY | O_APPEND | O_CREAT
/*  int fd = open("./01_open.txt",O_RDWR | O_CREAT | O_TRUNC,0777);
    if(fd < 0)
    {
        perror("open");
        return -1;
    }
    printf("fd = %d\n",fd);
    
    //write将数据写入到指定文件中
    //size_t write(int fd,const void* buf,size_t count)
    
    char str[20] = "hello";
    size_t res = 0;
    res = write(fd,str,sizeof(str));
    printf("res = %ld\n",res);
*/
    //从指定文件中读取数据
    //size_t read(int fd,const void* buf,size_t count)

    umask(0);//将umask清0

    int fd = open("./01_open.txt",O_RDONLY,0777);
    int fd1 = open("./001_open.txt",O_WRONLY | O_CREAT | O_TRUNC,0777);
    if(fd < 0)
    {
        perror("open1");
        return -1;
    }

    if(fd1 < 0)
    {
        perror("open2");
        return -1;
    }
    printf("fd = %d\n",fd);
    printf("fd1 = %d\n",fd1);

    char str1[22]="";
    size_t res = 0;
    //复制、read函数应用
    while(1)
    {
        bzero(str1,sizeof(str1));
        res = read(fd,str1,sizeof(str1)-1);
        if(0 == res)
        {
            printf("读取完毕\n");
            break;
        }
        else if(res < 0)
        {
            perror("read");
            break;
        }
        printf("res = %ld str1 = %s\n",res,str1);
    //  write(1,str1,res);
    }

    //粘贴
    res = write(fd1,str1,sizeof(str1));
    printf("res = %ld\n",res);



    if(close(fd)<0)
    {
        perror("close");
        return -1;
    }

    return 0;
}
                                                                                                                                                
                                                                                                                                                
                                                                                                                                                
                                                                                                                                                
                                                                                                                                                
                                                                                                                                                

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值