How to get the date and time of a file in C

2 Answers

0 votes
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>

struct tm *dt;
struct stat attrib;

int main(int argc, char **argv) 
{ 
    stat("d:\\data.txt", &attrib);
    
    dt = gmtime(&(attrib.st_mtime)); // Universal Time (UTC) or GMT timezone
    
    printf("Year: %d\n", dt->tm_year + 1900); // The number of years since 1900 
    printf("Month: %d\n", dt->tm_mon + 1); // month, range 0 - 11 
    printf("Day: %d\n", dt->tm_mday); // day of the month, range 1 - 31
    printf("Hour: %d\n", dt->tm_hour + 1); // hours, range 0 - 23 
    printf("Minute: %d\n", dt->tm_min); // minutes, range 0 - 59 
    printf("Second: %d\n", dt->tm_sec); // seconds,  range 0 - 59
    
    return(0);
}

/*
run:

Year: 2013
Month: 7
Day: 25
Hour: 20
Minute: 49
Second: 31

*/

 



answered Jun 16, 2015 by avibootz
edited Jun 16, 2015 by avibootz
0 votes
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdio.h>

// on windows with visual studio express

int main( void )
{
   struct _stat st;
   char timebuf[32];
   char* filename = "d:\\data.txt";
   errno_t err;
   int r;

   r = _stat(filename, &st);
   
   if (r != 0 )
   {
      switch (errno)
      {
         case ENOENT:
				printf("File %s not found.\n", filename);
				break;
         default:
				printf("Error on _stat()\n");
      }
   }
   else
   {
      err = ctime_s(timebuf, 32, &st.st_mtime);
      if (err)
         printf("Error in ctime_s()");
      
	  printf("File %s Date and time modified is : %s", filename, timebuf );
   }

   return 0;
}

/*
run:

File d:\data.txt Date and time modified is : Fri Dec 31 13:00:00 1999

*/


 

 



answered Jun 17, 2015 by avibootz

Related questions

1 answer 282 views
1 answer 133 views
1 answer 139 views
1 answer 117 views
117 views asked Aug 14, 2023 by avibootz
1 answer 252 views
...