1. 程式人生 > 實用技巧 >C庫使用(一)——檔案時間獲取並轉換

C庫使用(一)——檔案時間獲取並轉換

<sys/stat.h>庫檔案下的時間屬性預設是以秒為單位的,需要通過ctime函式進行轉換,標頭檔案為<ctime.h>。

程式碼如下所示

/*
 * @filename: level4_d3.c
 * @FilePath: \C Task\level4_d3.c
 * @Descripttion: 遍歷資料夾下所有檔案,並列印檔名、大小、日期等屬性
 * @version: V1.0
 * @Author: 
 * @Date: 2020-12-06 16:49:30
 * @LastEditors: Bi Jiaqin
 * @LastEditTime: 2020-12-06 16:50:22
 */


#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <time.h>

int main(int argc, const char *argv[])
{
	DIR *dir;
	int fd, f_num = 1;
	struct dirent *dent;
	struct stat buf;

	dir = opendir(".");

	if(dir)
	{
		while((dent = readdir(dir)) != NULL)
		{
			stat(dent->d_name, &buf);
		
			printf("編  號:%d  \n文 件 名: %s  \n大  小:%d  \n建立時間:%s修改時間:%s訪問時間:%s\n\n\n", f_num, dent->d_name, (int)buf.st_size, ctime(&buf.st_ctime), ctime(&buf.st_mtime), ctime(&buf.st_atime));
			f_num++;
		}
	}

	return 0;
}