Chinaunix首页 | 论坛 | 博客
  • 博客访问: 278186
  • 博文数量: 212
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 37
  • 用 户 组: 普通用户
  • 注册时间: 2013-06-07 11:07
文章分类

全部博文(212)

文章存档

2015年(90)

2013年(122)

我的朋友

分类: C/C++

2015-07-03 16:14:45

原文地址:struct stat的用法 作者:longmenyu

预备知识:
1.    函数名: lstat
      需要包含的头文件:
            #include

            #include 
  功 能: 获取一些文件相关的信息
  用 法: int lstat(const char *path, struct stat *buf);
  参数:
  path:文件路径名。
  buf:是以下结构体的指针
     
struct stat
{
dev_t st_dev; /* ID of device containing file -文件所在设备的ID*/
ino_t st_ino; /* inode number -inode节点号*/
mode_t st_mode; /* protection -保护模式?*/
nlink_t st_nlink; /* number of hard links -链向此文件的连接数(硬连接)*/
uid_t st_uid; /* user ID of owner -user id*/
gid_t st_gid; /* group ID of owner - group id*/
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 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 - */
};

2. lstat函数返回说明:
  成功执行时,返回0。失败返回-1,errno被设为以下的某个值
  EBADF: 文件描述词无效
  EFAULT: 地址空间不可访问
  ELOOP: 遍历路径时遇到太多的符号连接
  ENAMETOOLONG:文件路径名太长
  ENOENT:路径名的部分组件不存在,或路径名是空字串
  ENOMEM:内存不足
  ENOTDIR:路径名的部分组件不是目录

程序清单:

#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <ctime>

using namespace std;

int main(int argc,char *argv[])
{
    int rtn;
    struct stat buf;
    char *filename = "/home/eagle/test/readdir.c";

    rtn = stat(filename,&buf);
    if(rtn != 0)
    {
        perror("Failed");
    }
    else
    {
        cout<<"The size of "<<filename<<" in bytes:"<<buf.st_size<<endl;
        cout<<"The time of last access:"<<ctime(&buf.st_atime)<<endl;
        cout<<"The time of last modification:"<<ctime(&buf.st_mtime)<<endl;
        cout<<"The user ID is:"<<buf.st_uid<<endl;
    }
    return 0;
}

程序执行结果:
The size of /home/eagle/test/readdir.c in bytes:501
The time of last access:Thu Dec  9 16:56:31 2010

The time of last modification:Thu Nov 18 17:20:42 2010

The user ID is:1015
阅读(628) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~