C语言,在WINDOWS下取文件创建时间的问题?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C语言,在WINDOWS下取文件创建时间的问题?相关的知识,希望对你有一定的参考价值。

/*第一段代码,请高手看看为什么出错,能帮我改改吗,谢谢*/
#include<stdio.h>
#include<time.h>
#include <sys/stat.h>
main()

char buf[65];
struct stat sb;
stat("g:\\1.txt",&sb);
struct tm* t=localtime(&sb.st_ctime);
sprintf(buf,"%04d-%02d-%02d%02d:%02d:%02d",t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);

/*第二段代码,也请高手指教,谢谢*/
#include<stdio.h>
#include<time.h>
#include <sys/stat.h>
main()

time_t tt;
struct tm *tst;
struct stat st;
stat("G:\1.TXT",&st);
tt=st.st_ctime;//取文件创建时间并且赋值给tt
tst=localtime(&tt);//取本地时间格式
printf("%d\n",tt/3600/24/365);//根据秒数计算从1970年到现在已经多少年了
printf("%d\n",tst->tm_mon+1);//月份需要加上1才为当前的月份

使用_findfirst函数或_findnext函数检索磁盘上的文件能获取相关信息,其中就包含创建日期。
long _findfirst(const char*, _finddata_t *);
long _findnext(const long, _finddata_t *);
findfirst函数用一个文件名来启动一次检索,同时把能找到的第一个文件的数据存入_finddata_t所指向的结构体,然后返回本次检索的句柄,若失败返回-1L
findnext函数则接受一个检索句柄,寻找下一个有效的相关文件,把数据存入_finddata_t所指向的结构体,然后返回0,若失败,则返回非零。
参考技术A 给你参考一下下面的代码
#include <sys\stat.h>
#include <stdio.h>
#include <time.h>

#define FILENAME "TEST.$$$"

int main(void)

struct stat statbuf;
FILE *stream;

/* open a file for update */
if ((stream = fopen(FILENAME, "w+")) == NULL)

fprintf(stderr, "Cannot open output file.\n");
return(1);


/* get information about the file */
stat(FILENAME, &statbuf);

fclose(stream);

/* display the information returned */
if (statbuf.st_mode & S_IFCHR)
printf("Handle refers to a device.\n");
if (statbuf.st_mode & S_IFREG)
printf("Handle refers to an ordinary file.\n");
if (statbuf.st_mode & S_IREAD)
printf("User has read permission on file.\n");
if (statbuf.st_mode & S_IWRITE)
printf("User has write permission on file.\n");

printf("Drive letter of file: %c\n", 'A'+statbuf.st_dev);
printf("Size of file in bytes: %ld\n", statbuf.st_size);
printf("Time file last opened: %s\n", ctime(&statbuf.st_ctime));
return 0;
追问

/*第二段代码如下*/
#include
#include
#include
main()

time_t tt;
struct tm *tst;
struct stat st;
stat("e:\\1.txt",&st);//必须使用两个‘\\’
tt=st.st_ctime;
tst=localtime(&tt);
printf("%d\n",tt/3600/24/365);
printf("%d\n",tst->tm_mon+1);

本回答被提问者采纳
参考技术B 不知道你用什么编译器
第一个的 struct tm *t ,大部分情况下C 的所有变量定义需要语句前面,不然会报错(有些编译器可能没有这个规定)。

除这之外程序好象是没有问题追问

第一段代码是我找来的,我也不清楚怎么回事;第二段代码错误出在stat("G:\1.TXT",&st);中,应该使用两个'\\'来表示路径,神奇啊。。。。现在第二段代码已经编译成功了

windows 创建快捷方式 win32API C语言

代码如下:

// shortlink.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

// shortlink.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <Windows.h>
#include <ShObjIdl.h>
#

以上是关于C语言,在WINDOWS下取文件创建时间的问题?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 C 语言的 windows 的 %appdata% 路径中创建目录并创建文件

在c语言中怎样打开一个文本文档

C语言如何判断文本文档的结束

C语言文件的定义

C语言文件的定义

windows 创建快捷方式 win32API C语言