I have a code to check the last time modification of a file using "gmtime".
Is it possible to remove the seconds in the result?
Here is my code:
1 2 3 4 5
struct tm* clock; // create a time structure
struct stat attrib; // create a file attribute structure
stat("test.txt", &attrib); // get the attributes of afile.txt
clock = gmtime(&(attrib.st_mtime)); // Get the last modified time and put it into the time structure
struct stat attrib ;
::stat("test.txt", &attrib);
// make a copy of the std::tm
std::tm time_modified = *std::gmtime( &(attrib.st_mtime) ) ;
// modify the copy as you please
time_modified.tm_sec = 0 ; // set seconds to zero
Is it possible to remove the seconds in the result?
An alternative approach to JBorges's suggestion is to exploit integer division and the fact that a time_t is in units of seconds to truncate the time_t rather than the struct tm, e.g.
The two approaches are no better or worse if you want to truncate the time to the minute. But if you want to round instead, the time_t based approach is better than the struct tm approach as you don't have to worry about times within a second of midnight.
#include <iostream>
#include <ctime> // ******* C++ header for std::gmtime() etc.
int main()
{
std::time_t now = std::time(nullptr) ;
// make a copy of the std::tm
std::tm modified_time = *std::gmtime( &now ) ;
// modify the copy as you please
modified_time.tm_sec = 0 ; // set seconds to zero
modified_time.tm_year += 6 ; // move to six years later
// etc...
std::cout << "UTC: " << std::asctime( &modified_time ) ;
}
So if you are making multiple calls to gmtime or localtime, you might want to make an actual copy of the struct pointed to be the returned pointer for safety.
Or use one the safer, but not so standard, alternative functions (these both take the pointer to a struct tm which they then return to you):