• [zz]linux IO(function open read write close)


    unix系统可用的文件IO函数--打开文件,读取文件,写文件等。大致用到5个函数:open,read,write,lseek,close。另外不同的缓存器长度对read和write函数有影响。

    术语--不带缓存指的是每个read和write都调用内核中的一个系统调用。

    文件描述符:对于内核而言,所有打开文件都由文件文件描述符引用。文件描述符是一个非负整数,当打开一个现存文件或创建一个文件时,内核向进程返回一个文件描述符。惯例中unix shell是文件描述符0与进程的标准输入结合,文件描述符1与标准输出相结合,文件描述符2与标准出错输出项结合,这些只是管理,与内核无关。在POSIX.1应用程序中,幻数0,1,2被代换成符号常数STDIN_FILENO,STDOUT_FILENO,STDERR_FILENO。这些常数都定义在<unistd.h>中。 文件描述符的范围是0~OPEN_MAX,早期的Unix版本采用的上限是19(允许每个进程打开20个文件),现在很多系统则将其增加到63个。

    OPEN函数:调用open函数可以打开或常见一个文件。


    #include <sys/types.h>

    #include <sys/stat.h>

    #include <fcntl.h>

    int open(const char pathname,int oflag,.../*,mode _tmode*>);


    第三个参数写为...,这是ANSI C说明余下草书的数目和类型可以变化的方法。对于open函数而言,仅当创建新文件时菜使用第三个参数。

    Linux 常用c函数中这样定义:


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


     CREAT函数


    #include<sys/types.h>

    #include<sys/stat.h>

    #include<fcntl.h>

     int creat(const char * pathname,mode_t mode)


    CLOSE函数


    #include<unistd.h>

    int close(int filedes);


    LSEEK函数


    #include<sys/types.h>

    #include<unistd.h> 

    off_t lseek(int filedes,off_t offset,int whence);

    对参数offset的解释与参数whence的值有关:

    若whence是SEEK_SET,则将该文件的位移量设置为距文件开始处offset个字节

    若whence是SEEK_CUR,则将该文件的位移量设置为其当前值加offset,offset可为正或负

    若whence是SEEK_CUR,则将该文件的位移量设置为其当前值加offset,offset可为正或负


     READ函数


    #include<unistd.h>

    ssize_t read(int filedes,void * buff,size_t nbytes);

    如read成功,则返回读到的字节数。如已经到达文件的尾端,则返回0. 


    WRITE函数


    #include<unistd.h>

    ssize_t write(int filedes,const void * buff,size_t nbytes); 


     DUP和DUP2函数


    #include<unistd.h>

    int dup(int filedes);

    int dup2(int filedes,int filedes2);

    两个函数的返回:若成功为新的文件描述符,若出错返回-1 


     FCNTL函数


    #include<sys/types.h》

    #include<unistd.h>

    #include<fcntl.h>

    int fcntl(int filedes,int cmd,.../* int arg */);

    返回:若成功返回则依赖于cmd ,若出错返回-1

     fcntl函数有五种功能:

    复制一个现存的描述符(cmd=F_DUPFD)

    获得/设置文件描述符标记(cmd=F_GETFD/F_SETFD)

    获得/设置文件状态标志(cmd=F_GETFL/F_SETFL)

    获得/设置异步I/O所有权(cmd=F_GETOWN/F_SETOWN)

    获得/设置记录锁(cmd=F_GETLK,F_SETLK/F_SETLKW)

  • 相关阅读:
    假期训练七(hdu-2845 dp,hdu-1846,2188 巴什博奕)
    假期训练六(poj-1753,递归+hdu-2844,多重背包)
    假期训练五(poj-1077bfs+康拓展开,hdu-2577dp)
    1-10假期训练(hdu-2059 简单dp)
    1-9-假期训练心得(dp+bfs)
    如何在IntelliJ Idea中同时启动不同端口的两个实例
    搭建Springboot监控中心报错A attempt was made to call the method reactor.retry.Retry.retryMax(I)Lreactor/ret)
    使用spring中遇到"java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor"问题
    mvc:annotation-driven的前缀 "mvc"未绑定
    使用Idea构建springmvc框架,出现no bean named 'cacheManager' is defined 错误
  • 原文地址:https://www.cnblogs.com/yingzi/p/2860719.html
Copyright © 2020-2023  润新知