I'm caching some information from a file and I want to be able to check periodically if the file's content has been modified so that I can read the file again to get the new content if needed.
That's why I'm wondering if there is a way to get a file's last modified time in C++.
You can also see the modified date by viewing the file properties. Right-click the file and select Properties. In the Properties window, the Created date, Modified date, and Accessed date is displayed, similar to the example below.
Using getlastmod() Function: The getlastmod() function is used to get the last modification time of the current page.
ls command ls – Listing contents of directory, this utility can list the files and directories and can even list all the status information about them including: date and time of modification or access, permissions, size, owner, group etc.
The syntax is pretty simple; just run the stat command followed by the file's name whose last modification date you want to know, as shown in the example below. As you can see, the output shows more information than previous commands.
For example, to get the last modified time for the file ‘E:commands.docx’ the command would be: To get the modified date and time for all files and sub folders in the current directory the command would be: Using Forfiles command. Using forfiles command we can get modified date and time for all the files in a directory.
To get the last write time of a file in C#, use the LastWriteTime () method. For this, use the FileInfo as well as DateTime classes. Create an object of each −
You can run the below command to find the latest modified file in a directory. It would print the list of files in the order of file modified time. It would print the recently modified file at the bottom. /O:D will make the command print the files list using the file date/time attributes. /T:W will make the command use file modified time.
To get the modified date and time for all files and sub folders in the current directory the command would be: dir /T:W. To get modified date/time only for files in the current directory(i.e exclude directories from files) dir /T:W /A:-D.
There is no language-specific way to do this, however the OS provides the required functionality. In a unix system, the stat
function is what you need. There is an equivalent _stat
function provided for windows under Visual Studio.
So here is code that would work for both:
#include <sys/types.h> #include <sys/stat.h> #ifndef WIN32 #include <unistd.h> #endif #ifdef WIN32 #define stat _stat #endif auto filename = "/path/to/file"; struct stat result; if(stat(filename.c_str(), &result)==0) { auto mod_time = result.st_mtime; ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With