It returns non-NULL because the initial substring 29/Jan/20
matches the pattern (in particular, 20
matches the final %d
in the pattern).
If strptime()
returns non- NULL
, it returns a pointer to the next character after the part of the input string that matches the pattern. Thus, in this case, it will return a pointer to the character '1'
in the date string.
If you want to make sure that nothing is left in the input line, you need to check that the return value indicates a terminating zero at the end of the input line:
int main () { struct tm tm; char buffer [80]; char *str = "29/Jan/2012"; char *end = strptime(str, "%Y/%b/%d ", &tm); if (end == NULL || *end != '\0') exit(EXIT_FAILURE); if (strftime (buffer,80,"%Y-%m-%d",&tm) == 0) exit(EXIT_FAILURE); printf("%s\n", buffer);
Please note that I added the trailing space to the strptime()
template - this allows you to return spaces in the input file. If you do not want to allow this, use your original template.
source share