Thread: Grabbing stats on a file using unix command

  1. #1
    Registered User
    Join Date
    Sep 2011

    Grabbing stats on a file using unix command

    This is almost half my program. I'm currently working on it in small parts. The immediate problem is about grabbing file info using lstat and converting the time modified to local time.

    #include <sys/types.h>
    #include <sys/stat.h>
    #include <unistd.h>
    #include <stdio.h>
    #include <unistd.h>
    #include <time.h>
    #include <inttypes.h>
    int main( int argc, char** argv)
       for ( int i = 1; i < argc; i++)
          struct stat buffer;
          int stat = lstat(argv[i], &buffer);
          if ( stat != 0 )
             printf("Cannot open file %s.\n", argv[i]);
          char buf[1024];
          ssize_t len;
          if ((len = readlink(argv[i], buf, sizeof(buf)-1)) != -1)
              buf[len] = '\0';
          //printf("%zu\n", len);
          struct tm *tmz;
          time_t result = time(NULL);
          tmz = localtime(&buffer.st_mtime);
          printf("%s%ju secs since the Epoch\n",
            asctime(localtime(&result)), (uintmax_t)result);
          printf("year: %d mon: %d day: %d\n", 
            tmz->tm_year, tmz->tm_mon, tmz->tm_mday);
       return 0;
    Here is the output:

    ./l9stat ../loglog.big-o.gif       //<- some input file
    Sun Nov 27 15:43:24 2011
    1322437404 secs since the Epoch
    year: 111 mon: 10 day: 27
    The first line is the current time which is what I want. The second line is there for debugging. The last line isn't giving me what I want. It's supposed to print info about the input file I give it.

  2. #2
    Registered User
    Join Date
    Sep 2007
    localtime() returns a pointer to static storage that is overwritten each time localtime() is called. As such, you'll want to do "tmz = localtime(...)" after your printf() that also contains a localtime().

    In addition, the year as 111 is correct for files modified in 2011: tm_year is the number of years since 1900.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unix Command Interpreter Help
    By ashford74 in forum C Programming
    Replies: 14
    Last Post: 09-26-2008, 03:28 AM
  2. CUT command of UNIX IN C
    By bulbulred in forum C Programming
    Replies: 4
    Last Post: 05-28-2006, 09:13 AM
  3. Getting File stats
    By mbooka in forum C Programming
    Replies: 1
    Last Post: 04-05-2006, 08:05 PM
  4. unix command
    By axon in forum A Brief History of
    Replies: 5
    Last Post: 02-22-2004, 12:35 PM
  5. C implementation of unix ls command
    By sinkovich in forum Linux Programming
    Replies: 0
    Last Post: 02-24-2003, 04:38 AM