Rahul Rahul - 1 year ago 76
C Question

Getting incorrect file modification time using stat APIs

I see a strange behavior while fetching the modification time of a file.
we have been calling _stat64 method to fetch the file modification in our project as following.

int my_win_stat( const char *path, struct _stati64 *buf)
if(_stati64( path, buf) == 0)
std::cout<<buf->st_mtime << std::endl; //I added to ensure if value is not changing elsewhere in the function.

When I convert the epoch time returned by st_mtime variable using epoch convertor, it shows 2:30 hrs ahead of current time set on my system.

When I call same API as following from different test project, I see the correct mtime (i.e. according to mtime of file shown by my system).

if (_stat64("D:\\engine_cost.frm", &buffer) == 0)
std::cout << buffer.st_mtime << std::endl;

Even I called GetFileTime() and converted FILETIME to epoch time with the help of this post. I get the correct time according to time set the system.

if (GetFileTime(hFile, &ftCreate, &ftAccess, &ftWrite))
ull.LowPart = ftWrite.dwLowDateTime;
ull.HighPart = ftWrite.dwHighDateTime;

std::cout << (ull.QuadPart / 10000000ULL - 11644473600ULL);

What I am not able to figure out is why does the time mtime differ when called through my existing project?

What are the parameters that could affect the output of mtime ?

What else I could try to debug the problem further ?


  1. In VS2013, _stati64 is a macro which is replaced replaced by _stat64.

  2. File system is NTFS on windows 7.

Answer Source

An year later I ran into the similar problem but scenario is little different. But this time I understand why there was a +2:30Hrs of gap. I execute the C++ program through a perl script which intern sets the timezone 'GMT-3' and my machine had been in timezone 'GMT+5:30'. As a result there was a difference of '2:30Hrs'. Why ? As Harry mentioned in this post

changing the timezone in Perl is probably causing the TZ environment variable to be set, which affects the C runtime library as per the documentation for _tzset.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download