Reputation: 85
I used the following code segment to get the system time. But it results in a segmentation fault. Please help.
printf("Time : %s\n", System("time"));
return 0;
Upvotes: 0
Views: 2003
Reputation: 72629
The system() function returns an exit status (an int), not a string. Calling system("time")
prints the time to stdout. If that's what you want, just use
system("time");
You get a segfault because the int 0, when interpreted as a pointer for printf's %s
is a NULL pointer. Dereferencing NULL pointers is undefined behavior and a segmentation fault is one possibility for such undefined behavior.
Upvotes: 2
Reputation: 8065
Use the following code instead:
time_t t;
time(&t);
printf("%s", ctime(&t));
This will solve your problem.
Upvotes: 3
Reputation: 75588
The system() function returns an integer, while %s
indicates that you want to print a string. The system function does not return the result of the time
program, but the exit value.
Upvotes: 1
Reputation: 500207
I assume you mean system()
rather than System()
.
You seem to expect that system()
would return a string containing whatever the command has printed to the terminal. It does not do that. In fact, system()
returns the exit code of the child process.
The easiest way to get the current time is by using the time()
function:
NAME
time - get time in seconds
SYNOPSIS
#include <time.h>
time_t time(time_t *t);
DESCRIPTION
time() returns the time since the Epoch (00:00:00 UTC, January 1,
1970), measured in seconds.
If t is non-NULL, the return value is also stored in the memory pointed
to by t.
Upvotes: 2