linuxc 高級編程之文件操作3

題目要求:
   1.輸入文件名稱,能夠判斷文件類型,判斷實際用戶對該文件具有哪些存取權限;
2.要求打印出文件類型信息,inode節點編號,鏈接數目,用戶id,組id,文件大小信息;
3.修改文件的權限爲當前用戶讀寫,組內用戶讀寫,組外用戶無權限。

源代碼:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main(int argc,char* argv[])
{
 int i;
 char* str;
 for (i=1;i<argc;i++)
 {
  struct stat statbuf;
  if(lstat(argv[i],&statbuf)<0)
  {
   perror("lstat");
  }
  if(S_ISREG(statbuf.st_mode))
  str="a regular file";
  else
  str="not a regular file";
  printf("%s is %s\n",argv[i],str);
  printf("power is :%o\n",statbuf.st_mode);
  printf("inode is %ld\n",statbuf.st_ino);
  printf("linknum is %ld\n",statbuf.st_nlink);
  printf("uid is %d\n",statbuf.st_uid);
  printf("gid is %d\n",statbuf.st_gid);
  printf("size is %ld\n",statbuf.st_size);
  if(chmod(argv[i],S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP)<0)
   printf("chmod is error");
 }
 return 0;
}

stat()/fstat()/lstat()系統調用
功能
獲取文件狀態
頭文件
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
函數原型
int stat(const char *file_name, struct stat *buf);
int fstat(int filedes, struct stat *buf);
int lstat(const char *file_name, struct stat *buf);
與stat()差別:爲符號連接時,lstat()返回連接自身狀態
返回值
成功時返回0
否則-1

struct stat結構定義
struct stat {
    mode_t st_mode;  /*file type & mode*/
    ino_t     st_ino;     /*inode number (serial number)*/
    dev_t    st_rdev;   /*device number (file system)*/
    nlink_t   st_nlink;  /*link count*/
    uid_t     st_uid;     /*user ID of owner*/
    gid_t     st_gid;     /*group ID of owner*/
    off_t     st_size;    /*size of file, in bytes*/
    time_t   st_atime; /*time of last access*/
    time_t   st_mtime; /*time of last modification*/
    time_t   st_ctime;  /*time of last file status change*/
    long      st_blksize;     /*Optimal block size for I/O*/
    long      st_blocks;      /*number 512-byte blocks allocated*/
};

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