how to get the age of a file in linux?

Hi, I need to compare the last modified date of a file to the current time and determine if its over x minutes old.

I have been playing around but keep running into issues.

Anyone have any ideas? It would be MUCH appreciated!
Well, just use an ls -l (file), look for the date and time, then determine the age based upon those.
Well I meant how to do it in C++ :) I suppose I could do a system call ...

I was thinking of using stat in C but Im not great with C right now :)

Thanks

stat is the proper way to do it.
Im trying this now, it doesnt seem to work :


int fileAge;
char* command;
sprintf(command,'stat -c %Z ');
fileAge = system(command+" %s",strFileName);

Should I be escaping the %Z ? its part of the linux command. I tried that and get errors too.

As it stands ... the two lines above return this:

sqlcache.cc:49:19: warning: character constant too long for its type
sqlcache.cc: In function ‘int main(int, char**)’:
sqlcache.cc:49: error: invalid conversion from ‘int’ to ‘const char*’
sqlcache.cc:49: error: initializing argument 2 of ‘int sprintf(char*, const char*, ...)’
sqlcache.cc:49: warning: format not a string literal and no format arguments
sqlcache.cc:50: error: invalid operands of types ‘char*’ and ‘const char [4]’ to binary ‘operator+’

Use stat(2), not stat(1).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>

#include <cstring>
#include <cerrno> 
#include <ctime>

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

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        std::cerr << "Usage: " << argv[0] << " <filenames>" << std::endl;
        return 1;
    }
    
    struct stat buffer;
    
    for (int i = 1; i < argc; ++i)
    {
        int result = stat(argv[i], &buffer);
        if (result != 0)
        {
            std::cerr << argv[i] << ": " << strerror(errno) << std::endl;
            continue;
        }
        
        char datetime[100] = {0};
        const struct tm* time = localtime(&buffer.st_mtime);
        result = strftime(datetime, 100, "%c", time);
        
        std::cout << argv[i] << ": " << datetime << std::endl;
    }
    
    return 0;
}
Well, yes, system call was the intended way to do that. Except that it's evil.
Thank you PanGalactic. Ill try this as soon as I get home. Also thank you QWERTYman. Knowing what is evil will keep me from making really huge mistakes!

Topic archived. No new replies allowed.