Linux下C编程:常用系统调用接口小结(1)

来源:互联网 发布:淘宝直播obs 串流码 编辑:程序博客网 时间:2024/05/19 03:26

(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;}


0 0
原创粉丝点击