There are two problems with this function:
struct stat st; // declaration of the stat
struct tm *tm; //declaration of tm pointer
char getts(char *filename1)
{
char datestring[256];
stat(filename1, &st);
tm=localtime(&st.st_mtime);
strftime(datestring,sizeof(datestring),"%Y-%m-%d-%H.%M.%S" , tm);
return datestring;
}
First, it is defined as returning a char, but actually what you are returning is a char* (datestring is a char*, not a char). Second, you are returning a pointer to a local variable (the datestring is an array local to the getts function). This could lead to unpredictable results. To correct this, you must make this array static or global to the program.
char* getts(char *filename1)
{
static char datestring[256]; /* or make it global */
stat(filename1, &st);
tm=localtime(&st.st_mtime);
strftime(datestring,sizeof(datestring),"%Y-%m-%d-%H.%M.%S" , tm);
return datestring;
}
but even with this corrections we still have potential problems. This is because this function is not thread safe, and you should not use this approach in multi-threaded programs. The following changes will make the function thread safe:
char* getts(char *filename1, char *datestring, size_t datestringsize)
{
struct stat st; /* st and tm can not be global if you want to make this function */
struct tm tm; /* thread safe, so make them local. */
stat(filename1, &st);
/* use the reentrant (thread safe) version of localtime, localtime_r */
localtime_r(&st.st_mtime, &tm);
strftime(datestring,datestringsize,"%Y-%m-%d-%H.%M.%S" , &tm);
/* now you are returning a pointer to a user allocated buffer. User can do anything (change it) safely */
return datestring;
}
int
main(int argc, char *argv[])
{
/* user allocated buffer */
char datestring[256];
puts(getts("demo.c", datestring, sizeof(datestring)));
return 0;
}