Linux下对文件创建、修改、访问时间的一些操作

来源:互联网 发布:创业软件子公司 编辑:程序博客网 时间:2024/05/20 20:57
学习,stat,lstat,fstat
1 函数都是获取文件(普通文件,目录,管道,socket,字符,块()的属性。
函数原型
#include <sys/stat.h>

int stat(const char *restrict pathname, struct stat *restrictbuf);
提供文件名字,获取文件对应属性。
int fstat(int filedes, struct stat *buf);
通过文件描述符获取文件对应的属性。
int lstat(const char *restrict pathname, struct stat *restrictbuf);
连接文件描述命,获取文件属性。
2 文件对应的属性
struct stat {
mode_t st_mode; //文件对应的模式,文件,目录等
ino_t     st_ino;      //inode节点号
dev_t     st_dev;       //设备号码
dev_t     st_rdev;      //特殊设备号码
nlink_t   st_nlink;     //文件的连接数
uid_t     st_uid;       //文件所有者
gid_t     st_gid;       //文件所有者对应的组
off_t     st_size;      //普通文件,对应的文件字节数
time_t    st_atime;     //文件最后被访问的时间
time_t    st_mtime;     //文件内容最后被修改的时间
time_t    st_ctime;     //文件状态改变时间
blksize_t st_blksize;   //文件内容对应的块大小
blkcnt_t  st_blocks;    //伟建内容对应的块数量
};
可以通过上面提供的函数,返回一个结构体,保存着文件的信息。
长湖区的信息是文件的所有者和文件的模式。

#include
<iostream.h>//C++ 获得文件状态信息源码,C++ 获得文件所在磁盘盘符源码,C++ 文件创建时间源码,C++ 访问时间源码,C++ 最后修改日期源码,No such file or directory(无此文件或索引)
#include <time.h>#include <sys/types.h>#include <sys/stat.h>#include <stdio.h>void main( void ){    struct stat buf;    int result;    //获得文件状态信息    result =stat( "D:\ok2002.txt", &buf );    //显示文件状态信息   if( result != 0 )       perror( "显示文件状态信息出错" );//并提示出错的原因,如No such file or directory(无此文件或索引)    else    {        cout<<"文件大小:"<<buf.st_size<<"字节"<<endl;        cout<<"所在磁盘盘符 :";        cout<<char(buf.st_dev + 'A')<<endl;        cout<<"文件创建时间:"<<ctime(&buf.st_ctime);        cout<<"访问日期:"<<ctime(&buf.st_atime);//注意这里访问时间为00:00:00为正常        cout<<"最后修改日期:"<<ctime(&buf.st_mtime);   }}

相关函数:utimes, stat
表头文件:#include  <sys/types.h>
#include  <utime.h>
定义函数:int  utime(const  char *filename,  struct utimbuf  *buf)
函数说明:utime()用来修改参数filename文件所属的inode存取时间。结构utimbuf定义如下
struct  utimbuf{
time_t  actime;  /*存取时间*/
time_t  modtime;  /*更改时间*/
};

如果参数buf为空指针(NULL), 则该文件的存取时间和更改时间全部会设为目前时间

返回值:  成功0,  失败-1, 错误代码存于errno
错误代码:
EACCESS                   存取文件时被拒绝,权限不足
ENOENT                    指定的文件不存在



另外,用shell直接 ls -l 可以看到最后修改时间,ls-ul 可以看到最后访问时间

 

在Linux中,没有文件创建时间的概念。只有文件的访问时间、修改时间、状态改变时间。也就是说不能知道文件的创建时间。但如果文件创建后就没有修改过,修改时间=创建时间;如果文件创建后,状态就没有改变过,那么状态改变时间=创建时间;如果文件创建后,没有被读取过,那么访问时间=创建时间,这个基本不太可能。

  与文件相关的几个时间:

  1、访问时间,读一次这个文件的内容,这个时间就会更新。比如对这个文件使用more命令。ls、stat命令都不会修改文件的访问时间。

  2、修改时间,对文件内容修改一次,这个时间就会更新。比如:vi后保存文件。ls -l列出的时间就是这个时间。

  3、状态改变时间。通过chmod命令更改一次文件属性,这个时间就会更新。查看文件的详细的状态、准确的修改时间等,可以通过stat命令 文件名。

  比如: [jing@zhjh c]$ stat temp.c

  引用:

  File: 'temp.c'

  Size: 66 Blocks: 8 IO Block: 4096 \u4e00\u822c\u6587\u4ef6

  Device: 807h/2055d Inode: 1191481 Links: 1

  Access: (0664/-rw-rw-r--) Uid: ( 500/ jing) Gid: ( 500/ jing)

  Access: 2008-03-12 20:19:45.000000000 0800

  Modify: 2008-03-12 20:19:45.000000000 0800

  Change: 2008-03-12 20:19:45.000000000 0800

  说明:Access访问时间。Modify修改时间。Change状态改变时间。可以stat *查看这个目录所有文件的状态

 列取所有文件,并比较现在时间跟其创建时间的差,如果超过N天,则删除.

问题分解开来是:

1. 取得某个目录下面所有文件

2. 取得文件的创建日期

3. 取得当前日期跟其创建的日期差

4. 删除文件

为此,我写了一个小程序来测试

  1: // TestFileFunction.cpp : Defines the entry point for the console application.

   2: //

   3:  

   4: #include "stdafx.h"

   5:  

   6:  

   7: #include <stdio.h>//remove

   8: #include <io.h>

   9: #include <sys/stat.h>// get file info

  10: #include <time.h>

  11:  

  12: #include <iostream>

  13: using namespace std;

  14:  

  15: int main(int argc, char* argv[])

  16: {

  17:     printf("Hello World!\n");

  18:     

  19:  

  20:     int iresult; 

  21:     struct _stat buf; //in stat head file

  22:     //_FILE__ means the current file. you can assign another file name. IE D:\\test.txt"£©

  23:     iresult = _stat(__FILE__,&buf); 

  24:     

  25:  

  26:     //the seconds from Greenwich 1970-1-1 to now.

  27:     printf("seconds of file create-time  from 1970 :%d\n", buf.st_atime);

  28:  

  29:     //convert to our define format

  30:     //struct tm *localtime(long *clock)

  31:     long* m_sencodes = &buf.st_atime;

  32:     struct tm* m_localTime = localtime(m_sencodes);

  33:     printf("file Local time : %d:%d:%d\n", m_localTime->tm_hour,m_localTime->tm_min, m_localTime->tm_sec);

  34:  

  35:     //Get the current time

  36:     //

  37:     long* mptr_currentSeconds = new long;

  38:     time(mptr_currentSeconds);

  39:     printf("current seconds from 1970 :%d\n", *mptr_currentSeconds);

  40:     m_localTime = localtime(mptr_currentSeconds);

  41:     printf("current Local time : %d:%d:%d\n", m_localTime->tm_hour,m_localTime->tm_min, m_localTime->tm_sec);

  42:  

  43:     //compare the two times£¬second

  44:     //double difftime(time_t time2,time_t time1) 

  45:     long diffSeconds = difftime(*mptr_currentSeconds, *m_sencodes);

  46:     

  47:     const int SECONDS_OF_DAY= 86400;

  48:  

  49:     //how many days?

  50:     int diffDays = diffSeconds/SECONDS_OF_DAY;

  51:     printf("diff time seconds: %d, days: %d\n", diffSeconds, diffDays);

  52:  

  53:  

  54:  

  55:  

  56:     delete mptr_currentSeconds;

  57:  

  58:     //ok, now we will list all files in one folder

  59:     struct _finddata_t c_file;

  60:     long hFile;

  61:     

  62:     if ( (hFile = _findfirst("*.*", &c_file)) == -1L )

  63:         printf("No *.* files in current directory");

  64:     else

  65:     {

  66:         do

  67:         {

  68:             //we show files except sub-directory

  69:             if (c_file.attrib != _A_SUBDIR)

  70:             {

  71:                 printf("%s\n", c_file.name);

  72:             }

  73:             

  74:         }         while ( _findnext(hFile, &c_file) == 0 ) ;

  75:             

  76:         _findclose(hFile);

  77:     }

  78:  

  79:  

  80:  

  81:  

  82:  

  83:     

  84:  

  85:  

  86:  

  87:  

  88:  

  89:  

  90:     cin.get();

  91:  

  92:     return 0;

  93: }

  94:  

最后附上的是,时间日期函数的参考

<sys/stat.h>

     struct stat {
         dev_t      st_dev;    /* device inode resides on */
         ino_t      st_ino;    /* inode's number */
         mode_t     st_mode;   /* inode's mode */
         nlink_t    st_nlink;  /* number of hard links to the file */
         uid_t      st_uid;    /* user ID of owner */
         gid_t      st_gid;    /* group ID of owner */
         dev_t      st_rdev;   /* device type, for special file inode */
         struct timespec st_atimespec;  /* time of last access */
         struct timespec st_mtimespec;  /* time of last data modification */
         struct timespec st_ctimespec;  /* time of last file status change */
         off_t      st_size;   /* file size, in bytes */
         int64_t    st_blocks; /* blocks allocated for file */
         u_int32_t  st_blksize;/* optimal file sys I/O ops blocksize */
         u_int32_t  st_flags;  /* user defined flags for file */
         u_int32_t  st_gen;    /* file generation number */
     };

时间的转换

┌──────────────────────┐
│struct tm                                                     │
│{                                                                │
│ int tm_sec; /*秒,0-59*/                               │
│ int tm_min; /*分,0-59*/                               │
│ int tm_hour; /*时,0-23*/                              │
│ int tm_mday; /*天数,1-31*/                          │
│ int tm_mon; /*月数,0-11*/                           │
│ int tm_year; /*自1900的年数*/                     │
│ int tm_wday; /*自星期日的天数0-6*/             │
│ int tm_yday; /*自1月1日起的天数,0-365*/      │
│ int tm_isdst; /*是否采用夏时制,采用为正数*/   │
│}                                                                │
└──────────────────────┘
日期贮存结构date
┌───────────────┐
│struct date                              │
│{                                            │
│ int da_year; /*自1900的年数*/ │
│ char da_day; /*天数*/             │
│ char da_mon; /*月数 1=Jan*/ │
│}                                           │
└───────────────┘
时间贮存结构time
┌────────────────┐
│struct time                                 │
│{                                              │
│ unsigned char ti_min; /*分钟*/    │
│ unsigned char ti_hour; /*小时*/  │
│ unsigned char ti_hund;               │
│ unsigned char ti_sec; /*秒*/       │
│                                │
└────────────────┘
char *ctime(long *clock)
本函数把clock所指的时间(如由函time返回的时间)转换成数下列格式的字符串:
Mon Nov 21 11:31:54 1983n
char asctime(struct tm *tm)
本函数把指定的tm结构类的时间转换成下列格式的字符串:
Mon Nov 21 11:31:54 1983n
double difftime(time_t time2,time_t time1)
计算结构time2和time1之间的时间差距(以秒为单位)
struct tm *gmtime(long *clock)
本函数把clock所指的时间(如由函数time返回的时间)转换成格林威治时间,并以tm结构形式返回
struct tm *localtime(long *clock)
本函数把clock所指的时间(如函数time返回的时间)转换成当地标准时间,并以tm结构形式返回
void tzset()本函数提供了对UNIX操作系统的兼容性
long dostounix(struct date *dateptr,struct time *timeptr)
本函数将dateptr所指的日期,timeptr所指的时间转换成UNIX格式, 并返回自格林威治时间1970年1月1日凌晨起到现在的秒数
void unixtodos(long utime,struct date *dateptr,struct time *timeptr)
本函数将自格林威治时间1970年1月1日凌晨起到现在的秒数utime转换成DOS格式并保存于用户所指的结构dateptr和timeptr中
void getdate(struct date *dateblk)
本函数将计算机内的日期写入结构dateblk中以供用户使用
void setdate(struct date *dateblk)
本函数将计算机内的日期改成由结构dateblk所指定的日期
void gettime(struct time *timep)
本函数将计算机内的时间写入结构timep中, 以供用户使用
void settime(struct time *timep)
本函数将计算机内的时间改为由结构timep所指的时间
long time(long *tloc)
本函数给出自格林威治时间1970年1月1日凌晨至现在所经过的秒数,并将该值存于tloc所指的单元中.
int stime(long *tp)本函数将tp所指的时间(例如由time所返回的时间)写入计算机中.