1. 程式人生 > >【linux c learn 之stat】獲取檔案的屬性

【linux c learn 之stat】獲取檔案的屬性

NAME

       stat 獲取檔案屬性

這個函式位於<sys/stat.h>標頭檔案中

函式原型:

int  stat(const char *path, struct stat *buf);

引數:

path  檔案路徑+檔名

buf     指向buffer的指標

返回值:

-1   遇到錯誤

0    成功返回

函式作用:

把path檔案的資訊複製到指標buf所指的結構體中。

描述

stat結構體:

struct stat {
               dev_t     st_dev;     /* ID of device containing file */
               ino_t     st_ino;     /* inode number */
               mode_t    st_mode;    /* protection */
               nlink_t   st_nlink;   /* number of hard links */
               uid_t     st_uid;     /* user ID of owner */
               gid_t     st_gid;     /* group ID of owner */
               dev_t     st_rdev;    /* device ID (if special file) */
               off_t     st_size;    /* total size, in bytes */
               blksize_t st_blksize; /* blocksize for filesystem I/O */
               blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
               time_t    st_atime;   /* time of last access */
               time_t    st_mtime;   /* time of last modification */
               time_t    st_ctime;   /* time of last status change */
           };

dev_t包含裝置檔案的ID

st_inoi結點

st_mode檔案型別和許可許可權

st_nline檔案連結數

st_uid使用者所有者的ID

st_gid所屬組的ID

st_rdev裝置ID(如果指定檔案)

st_size 所佔的位元組數

st_blksize檔案系統I/O塊大小

st_block分配的512B大小的

st_atime最後訪問時間

st_mtime最後修改時間

st_ctime狀態最後改變時間

下面的POSIX巨集定義用於核對st_mode域的檔案型別

           S_ISREG(m)  是常規檔案?

           S_ISDIR(m)  目錄?

           S_ISCHR(m)  字元裝置?

           S_ISBLK(m)  塊裝置?

           S_ISFIFO(m) FIFO?

           S_ISLNK(m)  符號連結?  (Not in POSIX.1-1996.)

           S_ISSOCK(m) 套接字?  (Not in POSIX.1-1996.)

下面的標誌用於st_mode域:
           S_IFMT     0170000   bit mask for the file type bit fields
           S_IFSOCK   0140000   socket
           S_IFLNK    0120000   symbolic link
           S_IFREG    0100000   regular file
           S_IFBLK    0060000   block device
           S_IFDIR    0040000   directory
           S_IFCHR    0020000   character device
           S_IFIFO    0010000   FIFO
           S_ISUID    0004000   set-user-ID bit
           S_ISGID    0002000   set-group-ID bit (see below)
           S_ISVTX    0001000   sticky bit (see below)
           S_IRWXU    00700     mask for file owner permissions
           S_IRUSR    00400     owner has read permission
           S_IWUSR    00200     owner has write permission
           S_IXUSR    00100     owner has execute permission
           S_IRWXG    00070     mask for group permissions
           S_IRGRP    00040     group has read permission
           S_IWGRP    00020     group has write permission
           S_IXGRP    00010     group has execute permission
           S_IRWXO    00007     mask for permissions for others (not in group)
           S_IROTH    00004     others have read permission
           S_IWOTH    00002     others have write permission
           S_IXOTH    00001     others have execute permission

例項:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    struct stat info;
    
    if (argc != 2)
    {
        fprintf(stderr, "Usage: %s <pathname>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    if (stat(argv[1], &info) == -1)
    {
        perror("stat");
        exit(EXIT_FAILURE);
    }

    printf("File type;                  ");

    switch(info.st_mode & S_IFMT)
    {
        case S_IFBLK:   printf("block device\n");       break;
        case S_IFCHR:   printf("character device\n");   break;
        case S_IFDIR:   printf("directory\n");          break;
        case S_IFIFO:   printf("FIFO pipe\n");          break;
        case S_IFLNK:   printf("symlink\n");            break;
        case S_IFREG:   printf("regular file\n");       break;
        case S_IFSOCK:  printf("socket\n");             break;
        default:        printf("unknown\n");            break;
    }

    printf("I-node number:              %ld\n", (long)info.st_ino);
    printf("Mode:                       %lo(octal)\n",
            (unsigned long)info.st_mode);
    printf("Link count:                 %ld\n", (long)info.st_nlink);
    printf("Ownership:                  UID=%ld GID=%ld\n",
            (long)info.st_uid, (long)info.st_gid);

    printf("Preferred I/O block size:   %ld bytes\n",
            (long) info.st_blksize);
    printf("File size:                  %lld bytes\n",
            (long long) info.st_size);
    printf("Blocks allocated:           %lld\n",
            (long long) info.st_blocks);

    printf("Last status change:         %s", ctime(&info.st_ctime));
    printf("Last file access:           %s", ctime(&info.st_atime));
    printf("Last file modification:     %s", ctime(&info.st_mtime));

    exit(EXIT_SUCCESS);
}

執行結果:
[email protected]:~/linux_program/list$ ./stat stat.c
File type;                  regular file
I-node number:              679622
Mode:                       100644(octal)
Link count:                 1
Ownership:                  UID=1000 GID=1000
Preferred I/O block size:   4096 bytes
File size:                  2102 bytes
Blocks allocated:           8
Last status change:         Wed Jul 16 23:26:20 2014
Last file access:           Wed Jul 16 23:26:35 2014
Last file modification:     Wed Jul 16 23:26:20 2014


附錄為/usr/include/sys/stat.h原始碼:

/*-
 * Copyright (c) 1982, 1986, 1989 The Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)stat.h	7.11 (Berkeley) 3/3/91
 */

struct stat
{
	dev_t	st_dev;			/* inode's device */
	ino_t	st_ino;			/* inode's number */
	mode_t	st_mode;		/* inode protection mode */
	nlink_t	st_nlink;		/* number of hard links */
	uid_t	st_uid;			/* user ID of the file's owner */
	gid_t	st_gid;			/* group ID of the file's group */
	dev_t	st_rdev;		/* device type */
	off_t	st_size;		/* file size, in bytes */
	time_t	st_atime;		/* time of last access */
	long	st_spare1;
	time_t	st_mtime;		/* time of last data modification */
	long	st_spare2;
	time_t	st_ctime;		/* time of last file status change */
	long	st_spare3;
	long	st_blksize;		/* optimal blocksize for I/O */
	long	st_blocks;		/* blocks allocated for file */
	u_long	st_flags;		/* user defined flags for file */
	u_long	st_gen;			/* file generation number */
};

#define	S_ISUID	0004000			/* set user id on execution */
#define	S_ISGID	0002000			/* set group id on execution */
#ifndef _POSIX_SOURCE
#define	S_ISTXT	0001000			/* sticky bit */
#endif

#define	S_IRWXU	0000700			/* RWX mask for owner */
#define	S_IRUSR	0000400			/* R for owner */
#define	S_IWUSR	0000200			/* W for owner */
#define	S_IXUSR	0000100			/* X for owner */

#ifndef _POSIX_SOURCE
#define	S_IREAD		S_IRUSR
#define	S_IWRITE	S_IWUSR
#define	S_IEXEC		S_IXUSR
#endif

#define	S_IRWXG	0000070			/* RWX mask for group */
#define	S_IRGRP	0000040			/* R for group */
#define	S_IWGRP	0000020			/* W for group */
#define	S_IXGRP	0000010			/* X for group */

#define	S_IRWXO	0000007			/* RWX mask for other */
#define	S_IROTH	0000004			/* R for other */
#define	S_IWOTH	0000002			/* W for other */
#define	S_IXOTH	0000001			/* X for other */

#ifndef _POSIX_SOURCE
#define	S_IFMT	 0170000		/* type of file */
#define	S_IFIFO	 0010000		/* named pipe (fifo) */
#define	S_IFCHR	 0020000		/* character special */
#define	S_IFDIR	 0040000		/* directory */
#define	S_IFBLK	 0060000		/* block special */
#define	S_IFREG	 0100000		/* regular */
#define	S_IFLNK	 0120000		/* symbolic link */
#define	S_IFSOCK 0140000		/* socket */

#define	S_ISVTX	 0001000		/* save swapped text even after use */

#define S_BLKSIZE	512		/* block size used in the stat struct */

					/* 0666 */
#define	DEFFILEMODE	(S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)
#endif

#define	S_ISDIR(m)	((m & 0170000) == 0040000)	/* directory */
#define	S_ISCHR(m)	((m & 0170000) == 0020000)	/* char special */
#define	S_ISBLK(m)	((m & 0170000) == 0060000)	/* block special */
#define	S_ISREG(m)	((m & 0170000) == 0100000)	/* regular file */
#define	S_ISFIFO(m)	((m & 0170000) == 0010000)	/* fifo */
#ifndef _POSIX_SOURCE
#define	S_ISLNK(m)	((m & 0170000) == 0120000)	/* symbolic link */
#define	S_ISSOCK(m)	((m & 0170000) == 0140000)	/* socket */
#endif

#ifndef KERNEL
#include <sys/cdefs.h>

__BEGIN_DECLS
mode_t	umask __P((mode_t));
int	chmod __P((const char *, mode_t));
int	fstat __P((int, struct stat *));
int	mkdir __P((const char *, mode_t));
int	mkfifo __P((const char *, mode_t));
int	stat __P((const char *, struct stat *));
#ifndef _POSIX_SOURCE
int	fchmod __P((int, mode_t));
int	lstat __P((const char *, struct stat *));
#endif /* not POSIX */
__END_DECLS
#endif


相關推薦

linux c learn stat獲取檔案屬性

NAME       stat 獲取檔案屬性 這個函式位於<sys/stat.h>標頭檔案中 函式原型: int stat(const char *path, struct stat *buf);引數: path  檔案路徑+檔名 buf     指向bu

Linux學習筆記獲取檔案屬性stat()、fstat()、lstat()小結

相關文章 Linux是基於檔案的作業系統,一切皆檔案。下面就詳細的整理一下關於Linux檔案屬性的內容。 一、檔案屬性函式 系統提供了3個獲取檔案屬性的函式,分別是:stat()、fstat()、lstat()。 1、函式原型   標頭檔案包含:

linux C函式stat函式

1.函式功能: 通過檔名filename獲取檔案資訊,並儲存在buf所指的結構體stat中 2.函式原型 1)函式標頭檔案 #include <sys/stat.h> #include <unistd.h> 2)函式 int stat(const c

LINUX C學習筆記 3管道通訊2-標準流管道

從檔案結構體指標stream中讀取資料,每次讀取一行。讀取的資料儲存在buf指向的字元陣列中,每次最多讀取bufsize-1個字元(第bufsize個字元賦'\0'),如果檔案中的該行,不足bufsize個字元,則讀完該行就結束。如若該行(包括最後一個換行符)的字元數超過bufsize-1,則fgets只返

Linux學習筆記檔案檔案系統的壓縮,打包與備份

8.2Linux系統常見的壓縮指令   在 Linux 的環境中,壓縮檔案案的副檔名大多是: 『.tar, .tar.gz, .tgz, .gz, .Z, .bz2, *.xz』,為什麼會有這樣的副檔名呢?   這是因為 Linux 支援的壓縮指令非常多,且

linux C函式access函式的用法

1.函式功能: 檢查呼叫程序是否可以對指定的檔案執行某種操作。 2.函式原型: 1)函式標頭檔案 #include <stdio.h> #include <unistd.h> 2)函式 int access(

反射Field獲取字段

super setw print invoke return pri protect bsp 必須 ■getFields()、getDeclaredFields()、getField() 和 getDeclaredField()的用法 1 package refl

linux csetsockopt 詳解

多層 count 設置 例如 select() log struct rec 查找 轉自:http://blog.csdn.net/zhonglinzhang/article/details/9183229 功能描述: 獲取或者設置與某個套接字關聯的選

C++探索第二部分第一課:面向對象初探,string的驚天內幕

信息技術 false cli 方法 復雜 weixin include 命令 就是 內容簡單介紹 1、第二部分第一課:面向對象初探。string的驚天內幕 2

C#學習001.基本操作

arp main cti 字符 thread 程序 AI 報錯 float 001【HelloWorld】分析代碼塊 //這裏是註釋 下面是引入命名空間 using System; using System.Collections.Generic; using Syst

Linux C/C++ 第09講 HTTP協議與瀏覽器顯示網頁

   實現多執行緒檔案傳輸之後,就可以嘗試去實現瀏覽器顯示自定義網頁       因為瀏覽器訪問伺服器端的網頁是根據HTTP/HTTPS協議的         這需要先去了解HTTP/HT

Linux C/C++ 第08講 多執行緒TCP傳輸檔案/select模型

一、多執行緒    pthread.h    libpthread.so   -lpthread    1.建立多執行緒      1.1 程式碼   &nbs

Linux C/C++ 第07講 gdb除錯工具詳解

     當你需要單步跟蹤除錯的時候,就必然會用到gdb工具,不同於VS方便的除錯方式,gdb的除錯並不是那麼的方便直觀。不要降低熱情,熟練以後你會發現Linux下的程式設計方式非常好用。       一、簡介   &

Linux C/C++ 第06講 檔案IO

一 IO的基礎      1.1 認識核心物件              Linux不允許直接訪問核心裝置和記憶體,但可以通過核心系統函式去訪問      

C++模版神奇的Traits

介紹traits的文章很多,但感覺大部分文章的說明都很晦澀難懂,把一個並不很複雜的C++模板的應用描述的過於複雜。忍不住想把自己的理解跟大家分享一下,或許我也只是掌握了一點traits的皮毛而已,但也希望這些皮毛能略微抓住你的眼球,帶給你一些啟發。 首先,介紹traits前

Linux c字串的擷取

對字串的擷取: #include <stdio.h> #include <string.h> //截斷有特殊符號的字串,並取後段 void cutString_A(char* string) { char *p_start = string

Linux c大型專案的除錯技巧

巧妙利用列印資訊: 直接在函式裡面呼叫void print_trace(),就可以找到呼叫它的函式的層級關係 printf("!!!!!%s,%s,%d\n", __FILE__,__FUNCTION__, __LINE__); printf("!!!!!test->

linux CC語言中常用的幾個函式的總結

1、memset函式 定義變數時一定要進行初始化,尤其是陣列和結構體這種佔用記憶體大的資料結構。在使用陣列的時候經常因為沒有初始化而產生“燙燙燙燙燙燙”這樣的野值,俗稱“亂碼”。每種型別的變數都有各自的初始化方法,memset() 函式可以說是初始化記憶體的“萬能函式”,通常為新申請的記憶體進行初始化工作。

linux CC語言中常用的幾個函數的總結

有效 getchar() 調用 指向 ++ 再次 無法 linux c 收回 1、memset函數 定義變量時一定要進行初始化,尤其是數組和結構體這種占用內存大的數據結構。在使用數組的時候經常因為沒有初始化而產生“燙燙燙燙燙燙”這樣的野值,俗稱“亂碼”。每種類型的變量都有各

linux CC語言中常用的幾個函式的總結

3、fgets 雖然用 gets() 時有空格也可以直接輸入,但是 gets() 有一個非常大的缺陷,即它不檢查預留儲存區是否能夠容納實際輸入的資料,換句話說,如果輸入的字元數目大於陣列的長度,gets 無法檢測到這個問題,就會發生記憶體越界,所以程式設計時建議使用 fgets()。fgets() 的原型為