1. 程式人生 > >C++ 如何獲取目錄下面的檔案/檔案的建立時間

C++ 如何獲取目錄下面的檔案/檔案的建立時間

http://www.cnblogs.com/king_astar/archive/2009/09/27/1575107.html

我手上有一個C++程式會生成一些臨時檔案,過期以後希望能夠刪除. 到達成這個目的,我需要做到:

根據提供的路徑,

列取所有檔案,並比較現在時間跟其建立時間的差,如果超過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:  

   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所返回的時間)寫入計算機中.


   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:     
            
           

相關推薦

C++ 如何獲取目錄下面檔案/檔案建立時間

http://www.cnblogs.com/king_astar/archive/2009/09/27/1575107.html 我手上有一個C++程式會生成一些臨時檔案,過期以後希望能夠刪除. 到達成這個目的,我需要做到: 根據提供的路徑, 列取所有檔案,並比較

C++獲取目錄下的檔案

程式碼: #include <sys/types.h> #include <dirent.h> #include <unistd.h> #include <stdio.h> #include <iostream>

C/C++--C++獲取目錄下的檔案列表

#include <iostream> #include <io.h> #include <direct.h> #include <string> #include <vector&g

使用C++獲取目錄下的指定檔案:結構體_finddata_t 以及函式_findfirst、_findnext、_fineclose

    獲取資料夾裡面下面的相同的檔案是經常用的一個操作,比如我們需要獲取檔案下面所有的.exe檔案,這個時候我們就需要一個結構體和三個函式來幫助我們。     首先需要的結構體:struct _finddata_t     這

solaris修改目錄檔案建立時間(touch -t)

[[email protected]:/test]# ls -ll|grep dirtest1                 

Python 獲取檔案建立時間,修改時間和訪問時間

    # 用到的知識# os.path.getatime(file) 輸出檔案訪問時間# os.path.getctime(file) 輸出檔案的建立時間# os.path.getmtime(file) 輸出檔案最近修改時間 #-*- encoding=utf8 -*-imp

c/c++ 獲取目錄檔案列表

經過測試 Windows 和 Linux版本都可以執行。 windows版本 標頭檔案:io.h 關鍵函式:_findfirst、_findnext 關鍵結構體:_finddata_t struct _finddata_t {     unsigned attr

linux C++獲取目錄檔案列表

好像經常用到,那就記下來吧(遞迴遍歷子資料夾) #include <stdio.h> #include <stdlib.h> #include <string.h>

python資料夾遍歷,檔案操作,獲取檔案修改建立時間

在Python中,檔案操作主要來自os模組,主要方法如下: os.listdir(dirname):列出dirname下的目錄和檔案 os.getcwd():獲得當前工作目錄 os.curdir:返回當前目錄('.') os.chdir(dirname):改變工作目錄到

Windows下使用C++獲取目錄及子目錄下所有檔案

轉載自: BrowseDir.h #include <stdlib.h> #include <direct.h> #include <string.h> #include <string> #include <io

Linux下C語言獲取目錄中的檔案列表

struct stat info; stat(path,&info); if(S_ISDIR(info.st_mode))     printf("This is a directory");  stat結構及其域如下所示:           struct stat {              

linux下檔案建立時間、訪問時間、修改時間和改變時間

   Linux系統中沒有命令可以確切的檢視一個檔案的生成時間,但是可以知道訪問時間,修改時間,改變時間。 可以通過stat命令檢視一個檔案的訪問時間,修改時間,改變時間: 以下為三個時間的區別: 1、訪問時間(accesstime):讀取一次檔案的內容,該時間

Linux系統touch命令改變檔案建立時間

使用touch命令:將檔案的時間修改為2013年1月21日19點25分 touch -c -m -t 201301211925 version.dat 前提是必須有這個檔案。 解釋說明: -c表示不建立檔案  --no-create    do

C++瀏覽目錄下所有檔案(window和linux版本)

原本以為這麼常用的功能應該是標準C支援的,試了一下才發現不同平臺差異挺大。 參考部落格:https://blog.csdn.net/u012005313/article/details/50687297 上程式碼 test_dir.cpp #include <vector>

獲取目錄下所有檔案形成的樹狀圖

import java.io.File; /**  * 迭代指定目錄下的所有檔案,生成樹狀圖.  *  * @author Han Qi  *  */ public class FileTreeView {     /**      * 檔案前顯示' .'      *

Linux 下獲取目錄a下檔案b的操作

 最近在看Linux下檔案操作相關章節,遇到了這麼幾個結構體,被搞的暈乎乎的,今日有空,仔細研究了一下,受益匪淺。 DIR結構體類似於FILE,是一個內部結構,以下幾個函式用這個內部結構儲存當前正在被讀取的目錄的有關資訊(摘自《UNIX環境高階程式設計(第二版)》)

C#獲取從指定的檔案路徑,獲取檔案的圖示,然後顯示在image裡

 我是想動態的向toolstrip裡新增imagebutton,然後設定各項引數;ToolStripButton tsb = new ToolStripButton("aa");    tsb.Image =    //這個是設定imagebutton的圖片,是從指定的EXE檔案裡獲得圖片。不知道怎麼弄  

java獲取webroot下面檔案路徑

/** * * @return WebRoot目錄的絕對路徑 */ public static String getWebRootAbsolutePath() { String p

PHP 遍歷目錄下面所有檔案(案例)

<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style&g

C#獲取路徑下所有檔案以及子資料夾中檔案

/// <summary> /// 獲取路徑下所有檔案以及子資料夾中檔案 /// </summary> /// <param name="path">全路徑根目錄</param>