linuxc 高階程式設計之檔案操作3
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*/
};