Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timestamp of file in c++

Tags:

c++

timestamp

i want to check a file to see if its been changed and if it is, then load it again.. for this, i started with the following code which is getting me nowhere...

#include <sys/types.h>
#include <sys/stat.h> 
#include <unistd.h>
#include <iostream>

using namespace std;

int main()
{
    struct stat st;
    int ierr = stat ("readme.txt", &st);
    if (ierr != 0) {
            cout << "error";
    }
    int date = st.st_mtime;
    while(1){
            int newdate = st.st_mtime;
            usleep(500000);
            if (newdate==date){
                    cout << "same file.. no change" << endl;
            }
            else if (newdate!=date){
                    cout << "file changed" << endl;
            }
    }
}

all the code does is print same file.. no change continuously.

like image 572
Prasanth Madhavan Avatar asked Dec 01 '10 09:12

Prasanth Madhavan


1 Answers

That's because you're calling stat() outside the loop.

The result from stat() is correct at that particular moment. you need to call stat() again each time you want to check it.

like image 199
Roddy Avatar answered Oct 13 '22 22:10

Roddy