0

Reading info from files and printing them out. I save the modification time from stat as an int called mod_time into a struct to recall later. However, when I want to use the ctime()function, I run into a problem because that takes a time_t* type variable. I tried using a typecast but that just resulted in a seg fault. Any help would be much appreciated.

void print(struct file_info **array) { int i; for (i = 0; array[i] != NULL; i++) { printf("%s\n", array[i]->name); printf("mod_time: %s\n", ctime((time_t*)array[i]->mod_time)); } } 

The above is the example with the typecast, which yielded a seg fault. The original one just excluded the (time_t*) typecast, which resulted in a "without a cast" warning.

2
  • I don't mind saving the time as time_t; what bothers me is having to save it as a pointer, because then I have to deal with a triple line of pointers and I'm already overwhelmed enough as it is with deleting the two iterations of pointers I presently have. If I saved it as a regular time_t, how would I turn it into a pointer to be used by ctime()? Commented Sep 13, 2015 at 5:45
  • I think you can simply use & operator to get a pointer from a variable. example: &array[i]->mod_time Commented Sep 13, 2015 at 5:47

3 Answers 3

2

Since ctime function takes a pointer to time_t, I think a data of time_t must be on the memory, not only in an expression.

An example of making time_t data on the memory:

void print(struct file_info **array) { int i; for (i = 0; array[i] != NULL; i++) { time_t tmp = (time_t)array[i]->mod_time; /* I'm not sure if this works */ printf("%s\n", array[i]->name); printf("mod_time: %s\n", ctime(&tmp)); } } 
Sign up to request clarification or add additional context in comments.

Comments

2

Use of explicit casting in ctime((time_t*)array[i]->mod_time) is not right. You are taking an int and casting it to a pointer. It's not surprising that you get segmentation fault.

It will be better to use time_t for mod_time instead of an int.

If you don't have that option, you can use:

time_t t = array[i]->mod_time; printf("mod_time: %s\n", ctime(&t)); 

Comments

0

Assuming POSIX/C99 or more you could use a compound:

printf("mod_time: %s\n", ctime(&((time_t){array[i]->mod_time}))); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.