Daniel B
Daniel B

Reputation: 8879

Segmentation fault using ctime

I'm making a stat()-call that returns a struct with information that I want to extract. So far, I'm successful in getting what I want, until it comes to getting the time of access, modified and last change of the file.

I want to use ctime to get it, and then use printf to print it out.

    printf("File: %s",argv[1]);
    printf("\nSize: %d",result.st_size);
    printf("        Blocks: %d",result.st_blocks);
    printf("        IO Block: %d",result.st_blksize);
    printf("\nDevice: 0x%x",result.st_dev);
    printf("        Inode: %d",result.st_ino);
    printf("        Links: %d",result.st_nlink);
//  printf("\nAccess: %s",ctime(result.st_atime));

This code works well and gives the following output:

File: /etc/passwd
Size: 2250043           Blocks: 4416            IO Block: 4096
Device: 0x6804          Inode: 9738432          Links: 1

If I uncomment the last line where I want to get the access time, I get this output:

File: /etc/passwd
Size: 2250043           Blocks: 4416            IO Block: 4096
Segmentation fault

How can I fix this? Also, how come that I get a segmentation fault before the device, Inode and links get printed out? Shouldn't it be printed and then generate a segmentation fault?

I have about zero experience of C. I've studied Assembly in a previous course, but very briefly. I tried to read the API of time.h, but I couldn't really get to a solution.

I'm very grateful for any help or tips I can get!

Thanks, Z

Upvotes: 0

Views: 1834

Answers (2)

dmp
dmp

Reputation: 439

Please use

ctime(&result.st_atime)

and don't forget

#include <time.h>

Upvotes: 3

cnicutar
cnicutar

Reputation: 182639

The function ctime expects a const time_t *. You probably want:

printf("\nAccess: %s",ctime(&result.st_atime));
                            ^

Upvotes: 4

Related Questions