
HANDLE WINAPI FindFirstFile(
__in LPCTSTR lpFileName, //文件路径
__out LPWIN32_FIND_DATA lpFindFileData //文件属性信息
)
该函数可以获取文件制定文件包括时间在内的属性信息。这些信息包含在第二个参数执行的结构中:
typedef struct _WIN32_FIND_DATA {
DWORDdwFileAttributes
FILETIME ftCreationTime //文件创建时间
FILETIME ftLastAccessTime//文件访问时间
FILETIME ftLastWriteTime//最近一次修改时间
DWORDnFileSizeHigh
DWORDnFileSizeLow
DWORDdwReserved0
DWORDdwReserved1
TCHARcFileName[MAX_PATH]
TCHARcAlternateFileName[14]
} WIN32_FIND_DATA, *PWIN32_FIND_DATA, *LPWIN32_FIND_DATA
其中时间FILETIME结构体如下:
typedef struct _FILETIME {
DWORD dwLowDateTime
DWORD dwHighDateTime
} FILETIME, *PFILETIME
MSDN不推荐自己加减获取系统格式的时间,而是推荐使用
BOOL WINAPI FileTimeToSystemTime(
__in const FILETIME *lpFileTime, //上面获取的时间
__out LPSYSTEMTIME lpSystemTime //系统时间
)
这里获取的是系统时间:
typedef struct _SYSTEMTIME {
WORD wYear //年
WORD wMonth//月
WORD wDayOfWeek//周几
WORD wDay//日
WORD wHour//时
WORD wMinute//分
WORD wSecond//秒
WORD wMilliseconds//毫秒
} SYSTEMTIME, *PSYSTEMTIME
至此,时间成功获取
实例代码:
BOOL FileAttributes( LPCTSTR lpszFilePath/*文件路径*/ )
{
WIN32_FIND_DATA FindFileData = { 0 }
HANDLE hFile = ::FindFirstFile(lpszFilePath, &FindFileData)
if( INVALID_HANDLE_VALUE == hFile )
{ //handling error
return FALSE
}
SYSTEMTIME CreateTime = { 0 }//创建时间
SYSTEMTIME AccessTime = { 0 }//最近访问时间
SYSTEMTIME WriteTime = { 0 } //最近修改时间
if( !::FileTimeToSystemTime( FindFileData.ftCreationTime , &CreateTime) )
{
//handling error
return FALSE
}
if( !::FileTimeToSystemTime( FindFileData.ftLastAccessTime , &AccessTime) )
{
//handling error
return FALSE
}
if( !::FileTimeToSystemTime( FindFileData.ftLastWriteTime, &WriteTime))
{
//handling error
return FALSE
}
//OK 获取时间了,可以使用时间了
::CloseHandle( hFile )
return TRUE
}
如果用MFC实现就简单了点:
直接用
static void PASCAL SetStatus(
LPCTSTR lpszFileName,
const CFileStatus&status,
CAtlTransactionManager* pTM = NULL
)
这个静态成员就好了
struct CFileStatus
{
CTime m_ctime // creation date/time of file 创建时间
CTime m_mtime // last modification date/time of file 最近修改时间
CTime m_atime // last access date/time of file 最近访问时间
ULONGLONG m_size // logical size of file in bytes
DWORD m_attribute // logical OR of CFile::Attribute enum values
TCHAR m_szFullName[_MAX_PATH]// absolute path name
}
示例:
TCHAR* pFileName = _T("ReadOnly_File.dat")
CFileStatus status
CFile::GetStatus(pFileName, status)
//status中就有时间
//直接用CTime的Format函数格式化为随意形式的时间字符串格式即可
c语言可以通过stat()函数获得文件属性,通过返回的文件属性,从中获取文件大小。#include
<sys/stat.h>
可见以下结构体和函数
struct
stat
{
_dev_t
st_dev
_ino_t
st_ino
unsigned
short
st_mode
short
st_nlink
short
st_uid
short
st_gid
_dev_t
st_rdev
_off_t
st_size
//文件大小
time_t
st_atime
time_t
st_mtime
time_t
st_ctime
}
stat(const
char
*,
struct
_stat
*)
//根据文件名得到文件属性
参考代码:
#include <sys/stat.h>
void main( )
{
struct stat buf
if ( stat( "test.txt", &buf ) <0 )
{
perror( "stat" )
return
}
printf("file size:%d\n", buf.st_size )
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)