linux系统编程--read/write函数

  1. read/write函数
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
// read() attempts to read up to count bytes from file 
// descriptor fd into the buffer starting at buf.
ssize_t write(int fd, const void *buf, size_t count);
// write()  writes up to count bytes from the buffer 
// starting at buf to the file referred to by the file descriptor fd.

  1. 编程实现简单的cp功能
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>

int main(int argc, char* argv[])
{
    char buf[1024];
    int n = 0;

    int fd1, fd2;
    fd1=open(argv[1],O_RDONLY);
    if(fd1 == -1){
        perror("open argv1 error");
        exit(2);
    }

    fd2=open(argv[2],O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if(fd1 == -1){
        perror("open argv2 error");
        exit(1);
    }

    while((n=read(fd1,buf,1024)) != 0){
        if(n<0){
            perror("read error");
            break;
        }
        write(fd2,buf,n);
    }

    close(fd1);
    close(fd2);
    return 0;

}

3.错误处理函数
1、与 errno 相关

printf("xxx error: %d\n", errno);
char* *strerror(int errnum);
	printf("xxx error: %s\n", strerror(errno));

2、perror函数

void perror(const char* s);
	perror("xxx error");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值