码迷,mamicode.com
首页 > 其他好文 > 详细

stat()函数--------------获取文件信息

时间:2017-09-09 19:00:45      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:stat   pre   时间   argc   const   使用   hard link   dir   time   

stat():用于获取文件的状态信息,使用时需要包含<sys/stat.h>头文件。

函数原型:int stat(const char *path, struct stat *buf);

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 file system 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 */
};

示例:

int main(int argc, char* argv[])
{
    struct stat buf;
    char* path = "E:\\1.txt";

    int res = stat(path, &buf);
    if (res != 0)
    {
        perror("Problem getting information");
        switch (errno)
        {
        case ENOENT:
            printf("File %s not found.\n", path);
            break;
        case EINVAL:
            printf("Invalid parameter to _stat.\n");
            break;
        default:
            /* Should never be reached. */
            printf("Unexpected error in _stat.\n");
        }
    }

    //获取文件类型
    if (buf.st_mode & S_IFREG)
        printf("regular file\n");
    else if (buf.st_mode & S_IFDIR)
        printf("dir \n");
    else
        printf("other\n");

    //获取大小
    printf("SIZE %d\n", buf.st_size);


    char timeBuf[26] = { 0 };
    printf("%lld\n", buf.st_ctime);
    //文件最后访问时间
    errno_t err = ctime_s(timeBuf, 26,&buf.st_atime);
    if (err)
    {
        printf("Invalid arguments to ctime_s.");
        return -1;
    }
    printf("Time visit %s\n", timeBuf);

    //文件最后修改时间
    err = ctime_s(timeBuf, 26, &buf.st_mtime);
    if(err)
    {
        printf("Invalid arguments to ctime_s.");
        return -1;
    }
    printf("Time modified %s\n", timeBuf);
    
    system("pause");
    return 0;
}

示例及参考来源:https://docs.microsoft.com/zh-cn/cpp/c-runtime-library/reference/stat-functions

stat()函数--------------获取文件信息

标签:stat   pre   时间   argc   const   使用   hard link   dir   time   

原文地址:http://www.cnblogs.com/lianshuiwuyi/p/7498877.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!