Prasanth Madhavan
Prasanth Madhavan

Reputation: 13309

Timestamp of file in c++

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.

Upvotes: 5

Views: 14669

Answers (4)

Sadanand
Sadanand

Reputation: 1138

yes you have to move stat call in while loop. your while loop should look like this

while(1){
    ierr = stat ("/Volumes/Backup/song.rtf", &st);
    int newdate = st.st_mtime;
    usleep(500000);
    if (newdate==date){
        cout << "same file.. no change" << endl;
    }
    else if (newdate!=date){
        cout << "file changed" << endl;
    }
}

Upvotes: 0

CashCow
CashCow

Reputation: 31435

If you are on Linux and writing specifically for that platform you can use inotify to inform you when a file changes rather than continually polling it.

See man inotify to see how to use.

Upvotes: 0

dennycrane
dennycrane

Reputation: 2331

Well, you stat before the loop. The info you obtain by your initial stat is never updated. Move the call to stat into the while loop.

Upvotes: 2

Roddy
Roddy

Reputation: 68033

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.

Upvotes: 9

Related Questions