Linux下C編程:常用系統調用接口小結(1)

(1)mode_t umask(mode_t cmask):設置當前進程的文件創建屏蔽碼,這樣通過create或者open函數創建文件時,傳入的文件權限需要和這個值進行位運算,屏幕某些權限。

(2)int chmod(const char* filename, mode_t mode);

     int fchmod(int fd, mode_t mode); 改變文件的模式

(3)int chown(const char* filename, uid_t owner, gid_t  group);

    int fchown(int fd, uid_t owner, gid_t group);

     改變文件的所有權關係,包括所有者和所屬的組。

(4)int rename(const char* oldname, const char*newname); 文件重命名,調用是否成功跟oldname所表示文件指向普通文件還是目錄文件,newname所表示的文件是否已經存在有關係。

(5)int access(const char* pathname, int mode);判斷進程對文件是否有mode的訪問權限。

(6)int utime(const char* pathname, const struct utimebuf* times);修改文件的訪問時間和修改時間

(7)int stat(char* pathname, struct stat buf);

    int fstat(int fd, struct stat *buf);

    int lstat(char* pathname, stuct stat  *buf);

    獲取文件的狀態,lstat和stat功能相同,區別在於,對於符號鏈接文件,lstat返回的是該符號鏈接本身的信息,而stat返回的是符號鏈接所指向的文件的信息。


下面完成一個例子,這個例子,輸入一個文件名,測試文件類型,如果是普通文件,則將它的大小變爲0,但是維持它的訪問和修改時間不變。

   

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <utime.h>

#define runError 1;

int main(int argc, char* argv[]) {
  int  fd;
  struct stat statbuf;
  struct utimbuf times;
  if(argc != 2)
  {
	  printf("Usage: a filename\n");
	  return runError;
  }
  if(lstat(argv[1], &statbuf) < 0) //獲取文件狀態
  {
	  printf("error\n");
	  return runError;
  }

  if((statbuf.st_mode & S_IFMT)  != S_IFREG)
  {
	  printf("not regular file\n");
	  return runError;
  }

  fd = open(argv[1], O_RDWR);

  if(fd < 0)
  {
	  printf("%s open failed.\n", argv[1]);
	  return runError;
  }

  if(ftruncate(fd, 0) < 0) //截斷文件
  {
	  printf("%s truncate failed.\n", argv[1]);
	  return runError;
  }

  times.actime = statbuf.st_atim.tv_sec;
  times.modtime = statbuf.st_mtim.tv_sec;
  if(utime(argv[1], ×) == 0)
	  printf("utime() call sucessful \n");
  else
	  printf("utime() call failed \n");

  return 0;


}

(8)int dup2(int oldfd, int newfd);

可用來進行文件描述符重定向

/*
 ============================================================================
 Name        : dup2.c
 Author      : 
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define runError 1;
int main(int argc, char* argv[]) {
   int fd;
   if(argc != 2)
   {
		printf("Usage: a filename\n");
		return runError;
   }
   fd = open(argv[1], O_WRONLY|O_CREAT, 0644);

   if(fd < 0)
   {
 	  printf("%s open failed.\n", argv[1]);
 	  return runError;
   }

   if(dup2(fd, STDOUT_FILENO) == -1)
   {
	   printf("dup2 fd failed!\n");
	   return runError;
   }

   printf("dup2() call successed! \n");

   close(fd);

   return 0;
}


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