• IO学习系列之使用read和write复制文件内容


    • read函数:
    • 功能:从文件fd中读取count个字节,存放进指针buf
    • 具体内容:
    #include 
    
    ssize_t read(int fd, void *buf, size_t count);
    /*
    参数:
    
        	fd:	文件描述符
        	
        	buf:	用来存储读取内从的缓冲区的首地址
        	
        	count:	想要读取的字节数
        	
    返回值:
    
        	成功  	实际读取的字节数,且读到文件结尾会返回0
        	
        	失败  	-1  	重置错误码
    */
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • write函数:
    • 功能:把指针buf中的内容,写count个字节文件fd中;
    • 具体内容:
    #include 
    
    ssize_t write(int fd, const void *buf, size_t count);
    /*
    参数:
    
        	fd:	文件描述符
        	
        	buf:	要写入的数据的首地址
        	
        	count:	想要写入的字节数
        	
    返回值:
    
        	成功  	实际写入的字节数 (如果返回0,则表示没有写入内容)
        	
        	失败  	-1  	重置错误码
    */
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 示例代码:
    #include 
    #include 
    #include 
    #include 
    
    
    int main(int argc, const char *argv[]){
    
        if(3 != argc){
    
            printf("Usage : %s src_file dest_file\n",argv[0]);
    
            return -1;
        }
    
        int fd1 = open(argv[1],O_RDONLY);
    
        if(-1 == fd1)
        {
    
            perror("open error");
    
            return -1;
        
        }
        
        int fd2 = open(argv[2],O_WRONLY|O_CREAT|O_TRUNC,0666);
    
        if(-1 == fd2)
        {
    
            perror("open error");
    
            return -1;
        
        }
        
        int ret = 0;
        char buff[128] = {0};
    
        while(0 < (ret = read(fd1,buff,sizeof(buff)))){
            
    
            write(fd2,buff,ret);
    
    
        }
    
        close(fd1);
    
        close(fd2);
        
        
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
  • 相关阅读:
    使用 SMI 指标增强股票分析:amCharts JS Crack
    Reggie外卖项目 —— 移动端小程序之手机验证码登录
    flink cep
    基于SpringBoot+Vue的旅游管理系统
    2022辽宁省赛(A,B,D,E,F,G,I,M)
    初识React -- 一篇文章让你会用react写东西
    Nacos
    yolov1 论文精读 - You Only Look Once
    物理层
    基于ATX自动化测试解决方案
  • 原文地址:https://blog.csdn.net/qq_41878292/article/details/132993105