linux的read,write

      本来都不想写了,距离回宿舍还有一点时间,快速写一篇,因为从这里就要进入的系统编程,我们直接对内核进行调用,而对于那些高级语言的人们,他们是通过了类库,然后接触内核,这一块也要好好学习,今天入入门。

       我现在写代码都有自己的规范,变量每个写一行,不管怎么样都进行初始化,尽量不要出现魔鬼数字,比如返回-1,-2,直接用宏定义。fd文件描述符。我感觉这里的知识多的很,而且很细,想文件描述符应该写一个专题。这次先说明是入门,随便先写写

linux下的man open中

int open(const char *pathname, int flags);

int open(const char *pathname, int flags, mode_t mode)


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

先来个读read的代码的,那个0644应该先提一提,那个是个权限,我们用数字表示的,它传进去的是8进制。


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

#define LINELEN 256
#define ERROR    -1


int main(int argc,char *argv[])
{
    int fd = -1; 
    int rdsize = 0;
    char buf[LINELEN + 1] = {0};

    if(argc <= 1){ 
      printf("filename empty\n");
      return ERROR;
    }   

    if((fd = open(argv[1],O_RDWR | O_CREAT | O_APPEND,0644)) < 0){ 
      printf("open error[%d]\n",errno);                                                                               
      return ERROR;
    }   

    memset(buf,'\0',LINELEN);
    while((rdsize = read(fd,buf,LINELEN)) > 0){ 
        printf("%s",buf);
        memset(buf,'\0',LINELEN);
     }
        
    printf("\n");
    
    close(fd);
    
    return 0;
}  

对于连个代码对于buf数组都进行了

char buf[LINELEN + 1] = {0};
防止到第256字符的时候都没有遇到'\0',多加1个是为了防止越界,还有记得memset的头文件是string.h



在来个写write代码

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


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

#define LINELEN 256
#define ERROR   -1
int main(int argc,char *argv[])
{
    int fd = -1; 
    int rdsize = 0;
    char buf[LINELEN + 1] = {0};


    if(argc <= 1){ 
         printf("filename empty\n");
         return ERROR;
    }   

    if((fd = open(argv[1],O_RDWR | O_CREAT | O_APPEND,0644)) < 0){ 
         printf("open error[%d]\n",errno);
         return ERROR;
    }   
    sprintf(buf,"我会成为你的眼睛,为你看清未来\n");
    rdsize = write(fd,buf,strlen(buf));
    close(fd);
    return 0;
}

写好编译之后记得这样输入参数,像riven 和 anni都是文件名称,然后就可以打开在文件只看到


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值