你需要知道的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設計與實現等等一些高質量書籍,關注公衆號即可領取哦。
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章