loudking said:
I don't quite understand what does ((time_t)-1) mean when I execute
"man 2 time"
RETURN VALUE
On success, the value of time in seconds since the Epoch is
retu
rned.
On error, ((time_t)-1) is returned, and errno is set
appropriately
.
Could anybody tell me its meaning please?
And, is my way of checking return value correct?
time_t now;
time(&now);
if (!now) {
fprintf(stderr, "Unable to fetch time information: %s
\n",
strerror(errno));
return 1;
}
To clear up some confusion that's probably already been cleared up in
this thread:
The time function and the time_t type are standard C. The're declared
in the standard header <time.h>. If you want to use them, you need to
``#include <time.h>''. (If you don't ``#include <time.h>'', you can
get away with using the name "time_t" for your own purposes, but it
would be a very bad idea -- and that's not what you asked about
anyway.)
time_t is required by the C standard to be an arithmetic type. It
could be a signed integer type, an unsigned integer type, or a
floating-point type. It represents times, but the manner in which it
does so is not specified by the standard. (POSIX imposes stricter
requirements; for details, consult your system's documentation and/or
comp.unix.programmer.)
``-1'' is, of course, an integer expression of type int with the value
negative one. ``((time_t)-1)'' applies a cast operator to the value
-1, i.e., it converts the value from type int to type time_t. If
time_t is signed, the result is -1. If time_t is unsigned, the result
is the maximum value of the unsigned type. If time_t is
floating-point, the result is -1.0.
The value ``((time_t)-1)'' was chosen arbitrarily as a unique value
that indicates an error in the time() function. There are some
disadvantages to this choice; in particular, for some implementations
-1 represents an actual time. IMHO it would have been better to
define a symbolic constant and let the implementation choose a value.
But much of the C library definition is driven by historical practice,
so this is what we're stuck with.
To answer your second question, no, ``if (!now)'' is not the way to
test whether time time() function failed. When an expression is used
as a condition, it's considered false if it's equal to zero, true
otherwise. You need to test whether ``now'' is equal to -1, not to 0.