• LINUX下c/c++的学习(3)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)


  • 相关阅读:
    Fizz Buzz 问题
    旋转字符串
    合并排序数组
    尾部的零
    A + B 问题
    CentOS6.x安装RabbitMQ
    MySql游标
    MySql存储过程
    找出n个自然数(1,2,3,……,n)中取r个数的组合
    正则表达式
  • 原文地址:https://www.cnblogs.com/xFight/p/1631580.html
Copyright © 2020-2023  润新知