uc_day05

一,stat函數 
#include<sys/stat.h>
使用這個函數可以獲取文件的屬性。
int stat(const char *path,struct stat* buf);
第一個參數是輸入參數,第二個是輸出參數
成功返回0,失敗返回1


man -s2 stat


stat.c


#include<stdio.h>
#include<sys/stat.h>
#include<unistd.h>
#include<stdlib.h>


int main(){
   //獲取一個文件的屬性
   struct stat s = {};
   int res = stat("a.txt",&s);
   if(res == -1){
     perror("獲取文件屬性失敗");
     exit(-1);
   }else{
     printf("獲取文件屬性成功");
   }
   printf("i_node number:%d\n",s.st_ino);
   printf("mode:%d\n",s.st_mode);
   printf("硬連接數:%d\n",s.st_nlink);
   printf("文件屬主UID:%d\n",s.st_uid);
   
   return 0;
}


二,fstat函數
int fstat(int filedes,struct stat* buf);
使用這個函數,需要先打開文件


三,lstat函數
int lstat(const char *path,struct stat* buf);
主要用於獲取軟連接文件
#include<stdio.h>
#include<sys/stat.h>
#include<stdlib.h>
#include<unixstd.h>


int main(){
  struct stat s;
  stat("a.txt.sln",&s);//獲得的是a.txt的屬性
  printf("size:%d\n",s.st_size);
  lstat("a.txt.sln",&s);//獲取到的是a.txt.sln的屬性
  printf("size:%d\n",s.st_size);
  return 0;
}
//軟連接是快捷方式,對軟連接操作,等於對源文件的操作


四,access函數,測試文件是否具有某權限


五,權限屏蔽字
int main(){
  mode_t old = umask(0123);//本人無執行,同組無寫,其他無執行和寫
  int fd = open("abc",O_RDWR|O_CREAT,0666);
  umask(old);//恢復以前的權限屏蔽字
  return 0;
}


六,把虛擬地址映射到文件上
#include<stdio.h>
#include<sys/mman.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/types.h>
#include<stdlib.h>
#include<string.h>


struct Emp{
  int id;
  char name[10];
  int gender;
  double salary;
};


int main(){
  int fd = open("emp.dat",O_RDWR|O_CREAT|O_TRUNC,0666);
  //映射文件之前,要確保文件的大小一定夠用
  ftruncate(fd,sizeof(struct Emp)*3);
  if(fd == -1){}
  void* p = res = mmap(0,sizeof(struct Emp)*3,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
  if(p == MAP_FAILED){失敗}
  struct Emp* pe = p;
  pe[0].id = 100;
  strcpy(pe[0].name,"Daniel");
  pe[0].gender = 1;
  pe[0].salary = 23434;
  .......
  .......
  munmap(p,sizeof(struct Emp)*3);
  return 0;
}


//映射可以是私有映射,私有映射是寫到文件緩衝區裏面了
//映射進去只有自己的程序可以讀取,另外的程序不能讀取
//而共享映射不存在這個問題
//而映射到內存私有和共享無所謂,因爲都只有自己看到


七,readlink
用這個函數纔可以讀取到軟連接的真正內容,也就是源文件的內容


八,目錄操作
mkdir
rmdir//只能刪除空目錄,沒有刪除非空目錄的函數
getcwd//獲取當前目錄































































發佈了51 篇原創文章 · 獲贊 2 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章