0

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

1
  • printf is usually line buffered. Nothing gets printed until it sees a newline (by default). The newline is the last printf that fails, so the Device line won't appear on the screen. Commented Sep 9, 2012 at 12:19

2 Answers 2

4

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

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

Please use

ctime(&result.st_atime)

and don't forget

#include <time.h>
2
  • @Zyril: What are you doing compiling without a prototype for ctime() in scope? You should have your compilation warnings set so that you can't compile code without a prototype in scope (-Werror=missing-prototypes, for example, or at least -Wall), so that you can't get into such a mess. It is a self-protection measure. Commented Sep 9, 2012 at 12:29
  • Hello Jonathan! This is a course I'm taking to understand how the kernel works, and we are looking at system calls. I want to write a function in C that prints out the data in the struct that stat returns. I'm very new to this, so I'm not sure what you mean with prototype. I don't get any compilation warnings.
    – Daniel B
    Commented Sep 9, 2012 at 12:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.