【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_ino i结点

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

运行结果:

liujl@liujl-ThinkPad-Edge-E431:~/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



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 很高兴为您服务。您可以使用以下C语言代码来获取文件属性:struct stat st; if(stat("filename",&st)==0) { printf("文件大小:%d\n",st.st_size); printf("访问时间:%s\n",ctime(&st.st_atime)); printf("修改时间:%s\n",ctime(&st.st_mtime)); } ### 回答2: 在C语言中,我们可以使用标准库函数来获取文件属性。其中,常用的函数是`stat`和`lstat`。下面是使用`stat`函数来获取文件属性的示例代码: ```c #include <stdio.h> #include <sys/stat.h> int main() { char filename[100]; struct stat fileInfo; printf("请输入文件名:"); scanf("%s", filename); // 获取文件属性 if (stat(filename, &fileInfo) == 0) { // 文件类型 if (S_ISREG(fileInfo.st_mode)) { printf("文件类型:普通文件\n"); } else if (S_ISDIR(fileInfo.st_mode)) { printf("文件类型:目录\n"); } else if (S_ISLNK(fileInfo.st_mode)) { printf("文件类型:符号链接\n"); } else { printf("文件类型:其他\n"); } printf("文件大小:%lld 字节\n", fileInfo.st_size); printf("最后访问时间:%s", ctime(&fileInfo.st_atime)); printf("最后修改时间:%s", ctime(&fileInfo.st_mtime)); printf("最后状态改变时间:%s", ctime(&fileInfo.st_ctime)); } else { printf("获取文件属性失败\n"); } return 0; } ``` 以上代码先通过用户的输入获取文件名,然后调用`stat`函数来获取文件属性获取成功后,通过判断`st_mode`成员来确定文件类型(普通文件、目录、或符号链接),并输出文件大小、最后访问时间、最后修改时间和最后状态改变时间。 需要注意的是,文件的最后访问时间、最后修改时间和最后状态改变时间的值是一个`time_t`类型的整数值,需要通过`ctime`函数将其转换成可读的时间字符串。 ### 回答3: 要获取文件属性,可以使用C语言中的stat()函数。该函数能够获取文件的各种属性信息,比如文件类型、文件大小、权限等。 首先,在程序开头引入头文件<sys/stat.h>,该头文件定义了与文件属性相关的结构体和函数。 然后,使用stat()函数来获取文件属性。该函数的原型如下: int stat(const char *path, struct stat *buf); 其中,path是文件的路径和名称,buf是一个stat结构体指针,用来存储获取到的属性信息。 接下来,声明一个stat结构体变量,用于保存获取到的文件属性。 然后,使用stat()函数获取指定文件属性信息,将文件路径和名称作为参数传入,并将获取到的属性信息存储到前面声明的结构体变量中。 最后,可以根据需要,通过访问结构体变量中的成员来获取想要的属性信息。比如,通过访问st_size成员可以获取文件的大小;通过访问st_mode成员可以获取文件的权限。 下面是一个简单的示例代码: #include <stdio.h> #include <sys/stat.h> int main() { const char *filename = "test.txt"; struct stat file_attr; if (stat(filename, &file_attr) == 0) { printf("文件大小:%ld字节\n", file_attr.st_size); printf("文件权限:%o\n", file_attr.st_mode & 0777); } else { printf("获取文件属性失败。\n"); } return 0; } 上述代码中,假设要获取文件名为test.txt。首先,定义了一个stat结构体变量file_attr,然后使用stat()函数获取文件属性信息,并将结果存储到file_attr中。最后,利用printf函数打印出文件大小和文件权限。 注意,上述代码仅为示例,实际使用时还需根据具体需求进行适当的错误处理和参数校验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值