你需要知道的linux基础编程(五)

  1. Linux文件操作相关函数
    在这里插入图片描述

    1. stat函数、lstat函数(穿透函数和不穿透函数 都是相对于软链接来的)
      1. 头文件:
        1. #include<sys/types.h>
        2. #include<sys/stat.h>
        3. #include<unistd.h>
      2. 函数定义:
        1. Int stat(const * pathname,struct stat * buf); //穿透函数(追踪)
        2. Int lstat(const char * pathname,struct stat * buf); //不穿透函数(不追踪)
      3. 函数描述:获取文件的详细信息
      4. 参数说明:
        1. Pathname:文件的路径
        2. buf是stat结构体的一个指针
          1. stat结构体的定义:

             struct stat{
             	dev_t st_dev;     /*ID of device containing file文件的设备编号*/
             	ino_t    st_ino;    /*inode number节点*/
             	mode_t st_mode   /*protection文件的类型和存取权限*/
             	st_mode(这个变量占2byte,共16位)
             		掩码的使用:st_mode & 掩码
             		The following mask values are defined for the file mode component of the st_mode field:
             
             		S_ISUID 04000 set-user-ID bit
             		S_ISGID 02000 set-group-ID bit
             		S_ISVTX 01000 sticky bit
             		
             		S_IRWXU 00700 owner has read,write,and execute permission
             		S_IRUSR 00400 owner has read permission
             		S_IWUSR 00200 owner has write permission
             		S_IXUSR 00100 owner has execute permission
             		
             		S_IRWXG 00070 group has read,write,and execute permission
             		S_IRGRP 00040 group has read permission
             		S_IWGRP 00020 group has write permission
             		S_IXGRP 00010 group has execute permission
             		
             		S_IRWXO 00007 others(not in group) have read,write,and execute permission
             		S_IROTH 00004 others have read permission
             		S_IWOTH 00002 others have write permission
             		S_IXOTH 00001 others have execute permisson
             		
             		S_IFMT 0170000 bit mask for the file type bit field
             		文件类型
             		S_IFSOCK 0140000 socket
             		S_IFLNK 0120000 symbolic link(符号链接)
             		S_IFREG 0100000 regular file
             		S_IFBLK 0060000 block device
             		S_IFDIR 0040000 directory
             		S_IFCHR 0020000 character device
             		S_IFIFO 0010000 FIFO
             	Nlink_t st_nlink   /*number of hard links硬链接数目*/
             	Uid_t st_uid  /*user ID of owner用户ID*/
             	Gid_t st_gid  /*group ID of owner组ID*/
             	Dev_t st_rdev  /*device id (if special file)*/
             	Off_t st_size  /*total size,in bytes文件字节数*/
             	Blksize_t st_blksize  /*blocksize for filesystem I/O块大小*/
             	Blkcnt_t st_blocks  /*number of 512B blocks allocated分配512B的数目*/
             	
             	/*since linux 2.6, the kernel supports nanosecond precison for the following timestamp fields.自从linux2.6,内核支持十亿分之一秒的精确度对于下面的时间戳字段*/
             	Struct timespec st_atim  /*time of last access*/
             	Struct timespec st_mtim  /*time of last modification*/
             	Struct timespec st_ctim  /*time if last status change*/
             	
             #define st_atime st_aim.tv_sec /*backward compatibility向下兼容*/
             #define st_mtime st_mtim.tv_sec 
             #define st_ctime st_ctim.tv_sec
             };
            
      5. 函数返回值:
        on success,zero is returned.on error, -1 is returned, and errno is set approriately.
    2. access函数
      1. 作用:测试指定文件是否有某种权限
      2. 原型:
        1. Int access(const char *pathname,int mode)

        2. 参数:

           a) pathname:文件名
           b) mode:权限类别
           	i) R_OK是否有读权限
           	ii) W_OK是否有写权限
           	iii) X_OK是否有执行权限
           	iv) F_Ok测试一个文件是否存在
           	v) F_OK tests for the existence of the file.R_OK,W_OK,and X_OK test whether the file exists and grants read,write,and execute permissions,respectively.
          
        3. 返回值:
          a) 0 -->> 所有欲查核的权限都通过了检查
          b) -1 -->> 有权限被禁止

    3. chmod函数
      1. 头文件:
        #include<sys/stat.h>
      2. 函数定义:
        int chmod(const char * pathname,mode_t mode)
      3. 函数描述:
        chmod() changes the permissions of the file specified whose pathname is given in pathname,which is dereferenced if it is a symbolic link(符号链接)
      4. 参数说明
        1. pathname:文件的路径
        2. mode:权限设置
      5. 函数返回值:
        on success,zero is returned.on error,-1 is returned,and errno is set appropriately
    4. chown函数
      1. 头文件:
        #include<unistd.h>
      2. 函数定义:
        int chown(const char *pathname,uid_t owner,gid_t group)
        int fchown(int fd,uid_t owner,gid_t group)
        int lchown(const char * pathname,uid_t owner,gid_t group)
      3. 函数描述:
        These system calls changes the owner and group of a file. The chown(),fchown(),and lchown() system calls differ only in how file is specified:
        1. chown() changes the ownership of the file specified by pathname,which is dereferenced if it is a symbolic link
        2. fchown() changes the ownership of the file refered to by the open file descriptor fd
        3. lchown() is like chown().but dose not dereference symbolic links
      4. 函数参数:
        1. pathname:指的是文件的路径
        2. owner:用户id
        3. group:组id
      5. 函数返回值:
        on success,zero is returned. on error,-1 is returned,and errno is set appropriately
    5. truncate函数
      1. 头文件:
        1. #include<unistd.h>
        2. #include<sys/types.h>
      2. 函数定义:
        1. int truncate(const char * path,off_t length)
        2. int ftruncate(int fd,off_t length)
      3. 函数描述:
        1. the truncate() and ftruncate() functions cause the regular file named by path or referenced by fd to be truncated to a size of precisely length bytes.
        2. if the file previously was largerly than this size, the extra data is lost.if the file previous was shorter, it is extended,and the extend part read as null bytes("\0")
        3. the file offset is not changed
        4. if the size changed,then the st_ctime and st_mtime fields(respectively,time of last status change and time of last modification;see stat(2)) for the file are updated,and the set-user-id and set-group-id mode bits may be cleared.
        5. with ftruncate(),the file must be open for writing;with truncate(),the file must be writable.
      4. 函数参数:
        1. path:文件路径
        2. length:文件需要被调整的大小
          1. length大于文件大小,文件后面会填充空白字节或者空调
          2. length小于文件大小,文件多出的部分,会被舍弃
      5. 函数返回值:
        on success ,zero is returned.on error,-1 is returned,and errno is set appropriately
    6. 链接函数
      1. link函数
        1. 头文件:
          #include<unistd.h>
        2. 函数定义:
          int link(const char * oldpath,const char * newpath)
        3. 函数描述:
          1. link() create a new link (also known as a hard link) to an existing file
          2. if newpath exists, it will not overwritten
          3. this new name may be used exactly as the old one for any operation;both names refer to the same file(and so have the same permissions and ownership) and it is impossible to tell which name was the “original”
        4. 函数参数:
          1. oldpath:旧的文件的路径
          2. newpath:新文件的路径
        5. 函数返回值:
          on success, zero is returned.on error ,-1 is returned , and errno is set appropriately
      2. symlink函数
        1. 头文件:
          #include<unistd.h>
        2. 函数定义:
          int symlink(const char * target,const char * linkpath)
        3. 函数描述:
          symlink creates a symbolic link named linkpath which contains the string target.
        4. 函数参数:
          1. target:目标对象
          2. linkpath:创建软连接的路径
        5. 函数返回值:
          on success, zero is returned.on error ,-1 is returned , and errno is set appropriately
      3. readlink函数(只能读软链接)
        1. 头文件:
          #include<unistd.h>
        2. 函数定义:
          Ssize_t readlink(const char * pathname,char *buf,size_t bufsiz)
        3. 函数描述:
          readlink() places the contents of the symbolic link pathname in the buffer buf,which has size bufsiz. readlink() does not append a null byte to buf. It will truncate the contents(to a length of bufsiz characters),in case the buffer is too small to hold all of the contents
        4. 函数参数:
          1. pathname:文件的路径名
          2. buf:缓冲区
          3. bufsiz:缓冲区大小
        5. 函数返回值:
          on success, these calls return the number of bytes placed in buf. on error,-1 is returned and errno is set to indicate the error
      4. unlink函数
        1. 头文件:
          #include<unistd.h>
        2. 函数定义:
          int unlink(const char * pathname)
        3. 函数描述:
          1. unlink() deletes a name from the filesystem. If that name was the last link to a file and no processes have the file open, the file is deleted and the space it was using is made available for reuse.
          2. If the name was the last link to a file but any process still have the file open , the file will remain in existence until the last file descriptor referring to it is closed
          3. If the name refered to a symbolic link, the link is removed.
          4. If the name refered to a socket ,FIFO , or device , the name for it is removed but processes which have the object open may continue to use it
        4. 函数参数:
          pathname:文件的路径
        5. 函数返回值:
          on success, zero is returned.on error , -1 is returned, and errno is set appropriately
    7. rename函数
      1. 头文件:
        #include<stdio.h>
      2. 函数定义:
        int rename(const char * oldpath, const char * newpath)
      3. 函数描述:
        1. rename() renames a file,moving it between directories if required. Any other hard links to the file (as created using link(2)) are unaffected. Open file descriptor for oldpath are also unaffected.
        2. If newpath already exists, it will be atomically replaced replaced (subject to a few conditions; see ERRORS below), so that there is no point at which another process attempting to access newpath will find it missing.
        3. If oldpath and newpath are existing hard links referring to the same file, then rename() does nothing, and returns a success status.
        4. If newpath exists but operation fails for some reason, rename() guarantees to leave an instance if newpath in place
        5. oldpath can specify a directory. In this case, newpath must either not exist, or it must specify an empty directory.
        6. However, when overwriting there will probably be a window in which both oldpath and newpath refer to the file being renamed.
        7. If oldpath refers to a symbolic link, the link is renamed; if newpath refers to a symbolic link, the link will be overwritten.
      4. 函数参数:
        1. oldpath:源文件路径
        2. newpath:新文件路径
      5. 函数返回值:
        on success, zero is returned. on error , -1 is returned , and errno is set appropriately.
  2. Linux目录操作相关函数

    1. chdir函数
      1. 头文件:
        #include<unistd.h>
      2. 函数原型:
        int chdir(const char * path);
      3. 函数描述:
        chdir() changes the current working directory of the calling process to the directory specified in path
      4. 函数参数:
        1. path:文件的路径
      5. 函数返回值:
        1. on success,zero is returned. on error, -1 is returned, and errno is set approproately
    2. getcwd函数
      1. 头文件:
        #include<unistd.h>
      2. 函数原型:
        1. char * getcwd(char * buf, size_t size);
        2. char * getwd(char * buf);
      3. 函数描述:
        获取当前进程的工作目录
      4. 函数参数:
        1. buf:缓冲区
        2. size:缓冲区大小
      5. 函数返回值:
        1. on success, these functions return a pointer to a string containing the pathname of the current working directory. In the case getcwd() and getwd() this is the same value as buf
        2. on failure, these functions return null, and errno is set to indicate the error. The contents of the array pointed to by buf are undefined on error.
    3. mkdir函数
      1. 头文件:
        1. #include<sys/stat.h>
        2. #include<sys/types.h>
      2. 函数原型:
        int mkdir(const char * pathname,mode_t mode)
      3. 函数描述:
        1. mkdir() attempts to create a directory named pathname
        2. The argument mode specifies the mode for the new directory. It is modified by the process’s umask in the usual way: in the absence of a default ACL, the mode of the created directory is (mode & ~umask & 0777). Whether other mode bits are honored for the created directory depends on the operating system.
      4. 函数参数:
        1. Pathname:目录的路径
        2. Mode:目录的权限
      5. 函数返回值:
        mkdir() return zero on success, or -1 if an error occurred (in which case,errno is set appropriately)
    4. rmdir函数
      1. 头文件:
        #include<unistd.h>
      2. 函数原型:
        int rmdir(const char * pathname)
      3. 函数描述:
        rmdir() deletes a directory, which must be empty.
      4. 函数参数:
        pathname: 目录的路径
      5. 函数返回值:
        On success, zero is returned. On error, -1 is returned, and errno is set approproately.
    5. opendir函数
      1. 头文件:
        1. #include<sys/types.h>
        2. #include<dirent.h>
      2. 函数原型:
        DIR *opendir(const char * name);
      3. 函数描述:
        The opendir() function opens a directory stream corresponding to the directory name, and returns a pointer to the directory stream. The stream is positioned at the first entry in the directory.
      4. 函数参数:
        mame:文件的名字
      5. 函数的返回值:
        The opendir() functions return a pointer to the directory stream. On error, NULL is returned, and errno is set appropriately.
    6. readdir函数
      1. 头文件:
        #include<dirent.h>

      2. 函数原型:
        struct dirent * readdir(DIR * dirp)

      3. 函数描述:

        1. The readdir() function returns a pointer to a dirent structure representing the next directory entry in the directory stream pointed to by dirp. It returns null on reaching the end of the directory stream or if an error occurred.

        2. on Linux, the dirent structure is defined as follow:

           struct dirent{
           	ino_t d_ino;/*inode number*/
           	off_t d_off;/*not an offset*/
           	unsigned short d_reclen;/*length of this record*/
           	unsigned char d_type;/*type of file*/
           	char d_name[256];/*filename*/
           };
          
      4. 函数参数:
        dirp: 目录指针

      5. 函数的返回值:
        on success , readdir() returns a pointer to a dirent structure.if the end of the directory stream is reached, NULL is returned and errno is not changed. If an errno occurs, NULL is returned and errno is set appropriately

    7. closedir函数
      1. 头文件:
        1. #include<sys/types.h>
        2. #include<dirent.h>
      2. 函数原型:
        1. Int closedir(DIR * dirp);
          3 函数描述:
          The close() function closes the directory stream associated with dirp. A successful call to closedir() also closes the underlying file descriptor associated with drip. The directory stream descriptor dirp is not available after this call.
      3. 函数参数:
        dirp:目录指针
      4. 函数返回值:
        The closedir() function returns 0 on success. On error, -1 is returned, and errno is set appropriately.
  3. fcntl函数
    改变文件已经打开的文件和进程的属性

  4. dup、dup2函数

    1. 头文件:
      #include<unistd.h>
    2. 函数原型:
      1. Int dup(int oldfd);
      2. Int dup2(int oldfd,int newfd);
    3. 函数描述:
      1. The dup() system call creates a copy of the file descriptor oldfd,using the lowest-numbered unused descriptor for the new descriptor.
      2. After a successful return, the old and new file descriptors may be used interchangeably. They refer to the same open file description and thus share file offset and file status flags; for example , if the file offset is modified by using lseek() on one of the descriptors, the offset is also changed for the other.
      3. The dup2() system call performs the same task as dup(), but instead of using the lowest-numbered unused file descriptor, it uses the descriptor number specified in newfd. If the descriptor newfd was previously open, it is silently closed before being reused.
      4. The steps if closing and reusing the file descriptor newfd are performed atomically. This is important, because trying to implement equivalent functionality using close() and dup() would be subject to race conditions, whereby newfd might be reused between the two steps. Such reuse coulld happen because the main program is interrupted by a signal handler that allocates a file descriptor, or because a parallel thread allocates a file descriptor.
      5. note the following points:
        1. If oldfd is not a valid file descriptor, then the call fails, and newfd is not closed.
        2. If oldfd is a valid file descriptor, and newfd has the same values as oldfd, the dup2() does nothing, and returns newfd.
    4. 函数参数 :
      1) oldfd:旧的文件按描述符
      2) newfd:新的文件描述符
    5. 函数返回值:
      on success, these system calls return the new descriptor. on error, -1 is returned, and errno is set appropriately.
  5. 索引节点

    1. 索引节点inode:保存的其实是实际的数据的一些信息,这些信息成为“元数据”(也就是对文件属性的概述)。例如:文件大小,设备标识符,用户组标识符,文件模式,扩展属性,文件读取或修改的时间戳,链接数量,指向存储该内容的磁盘区块的指针,文件分类等等
      (注意数据分成:元数据+数据本身)

    2. 注意inode是怎样生成的:每个inode节点的大小,一般是128字节或256字节。inode节点的总数,在格式化时就给定(现在OS可以动态变化),一般2KB就设置一个inode。一般文件系统中很少有文件小于2KB,所以预定按照2KB分,一般inode是用不完的。所以innode在文件系统安装的时候会有一个默认数量,后期会根据实际的需要发生变化。

    3. 注意innode号:innode号是唯一的,表示不同的文件。其实在Linux内部的时候,访问文件都是通过inode号来进行的,所谓文件名仅仅是给用户容易使用的。当我们打开一个文件的时候,首先,系统找到这个文件名对应的inode号;然后,通过innode号,得到inode信息,最后,有inode找到文件数据所在的block,现在可以处理文件数据了。

    4. inode和文件的关系:当创建一个文件的时候,就给文件分配了一个innode。一个inode只对应一个实际文件,一个文件也会只有一个inode。inodes最大数量就是文件的最大数量


下面的是笔者的微信公众号,欢迎关注,会持续更新c++、python、tensorflow、机器学习、深度学习、计算机视觉等系列文章,公众号中内含300+本pdf电子书籍,肯定有你需要的一本,关注公众号即可领取哦。
在这里插入图片描述
如果你对JAVA方面感兴趣,可以关注下面JAVAERS公众号,陪你一起学习,一起成长,一起分享JAVA路上的诗和远方。在公众号里面都是JAVA这个世界的朋友,公众号每天会有技术类文章,面经干货,也有进阶架构的电子书籍,如Spring实战、SpringBoot实战、高性能MySQL、深入理解JVM、RabbitMQ实战、Redis设计与实现等等一些高质量书籍,关注公众号即可领取哦。
在这里插入图片描述

发布了46 篇原创文章 · 获赞 187 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Xiao_Jie123/article/details/105323955
今日推荐