• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 191
  • Last Modified:

How to get a file's timestamp from within C?

I need to compare the timestamps of two files on disk from within a C program.  Can I do a system call, pipe the response from an 'ls' to a string, then parse the string (this is on a *nix system)?  Or is there an easier way?

Thanks
0
jimdgar
Asked:
jimdgar
2 Solutions
 
grg99Commented:
I'd do a stat() to get the file info.

0
 
jkrCommented:
As grg99 wrote, 'stat()' is the way to go:

/* STAT.C: This program uses the _stat function to
 * report information about the file named STAT.C.
 */

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

void main( void )
{
   struct stat buf;
   int result;

   /* Get data associated with "stat.c": */
   result = stat( "stat.c", &buf );

   /* Check if statistics are valid: */
   if( result != 0 )
      perror( "Problem getting information" );
   else
   {
      /* Output some of the statistics: */
      printf( "File size     : %ld\n", buf.st_size );
      printf( "Time modified : %s", ctime( &buf.st_atime ) );
   }
}
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now