ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Hi All, I'm a c++ beginner. I get this code working just fine :
int main ()
{
time_t now = time(0);
struct tm tstruct;
char buf[11];
tstruct = *localtime(&now);
strftime(buf,sizeof(buf),"%Y-%m-%d", &tstruct);
printf(buf);
return 0;
} //result 2012-06-07
I need to called it several times so I turned it to function like this :
char GetDate()
{
time_t now = time(0);
struct tm tstruct;
char buf[11];
tstruct = *localtime(&now);
strftime(buf,sizeof(buf),"%Y-%m-%d", &tstruct);
return buf;
}
int main()
{
printf(GetDate()); // This is the final goal
return 0;
}
can't manage it to work. Also tried with std::string and ostringstream with no luck. It's obviously my lack of knowledge about data types and handling in c++. What is the right codes to obtain string output from a function? Thanks in advance.
char GetDate() will return a single char. Probably you want: char *GetDate(), but there are other problems as well:
buf is visible only inside the function GetDate, so return buf may cause a segmentation fault in main. You would better use global buffer instead of a local one.
char GetDate() will return a single char. Probably you want: char *GetDate(), but there are other problems as well:
buf is visible only inside the function GetDate, so return buf may cause a segmentation fault in main. You would better use global buffer instead of a local one.
segmentation fault still occured even using a global var.
Could you please show me your codes to get the line printf(GetDate()); working, if you dont mind. Thanks
try bigger buffer and try to debug your code to find out where the segfault occurred.
also you can try to insert printf ("Entering GetDate\n"); printf ("Exiting GetDate\n"); printf("before localtime"), "before strtime".... instead of debugging to find out where is the error. You can write:
Code:
main () {
char *r = GetDate();
printf(r);
}
and also with global buffer you do not need to return anything from GetDate, you just need to print the content of this buffer.
Actually there is no return value set in your GetDate, so printf(GetDate()) will fail. Have you got a compile message? You should use -Wall and take care about warnings also (there should be a message about this missing return value).
try bigger buffer and try to debug your code to find out where the segfault occurred.
also you can try to insert printf ("Entering GetDate\n"); printf ("Exiting GetDate\n"); printf("before localtime"), "before strtime".... instead of debugging to find out where is the error.
I always did that trick too. Actually I cant get it clean compiled.
[QUOTE=pan64;4697683]You can write:
Code:
main () {
char *r = GetDate();
printf(r);
}
This code compiled ok but still generated segmentation fault error;
Quote:
Originally Posted by pan64
and also with global buffer you do not need to return anything from GetDate, you just need to print the content of this buffer.
Actually there is no return value set in your GetDate, so printf(GetDate()) will fail. Have you got a compile message? You should use -Wall and take care about warnings also (there should be a message about this missing return value).
Thanks a lot, I just need to print the buffer and I always check the compiler's messages.
You do not need return value at all, you can simply write: void GetDate() because the result is stored in buf. Otherwise what do you want to return?
If you want to return the result (instead of using a global) you need to malloc storage area and return the pointer to that. And also you need to free that memory after printf.
_____________________________________
If someone helps you, or you approve of what's posted, click the "Add to Reputation" button, on the left of the post.
Happy with solution ... mark as SOLVED
(located in the "thread tools")
Because datebuf is marked static, it exists in the data segment instead of stack; it always exists, but is accessible only within the function itself. It is basically a global variable, but only known to the function body.
You can use the function for example thus:
Code:
int main(void)
{
printf("Today is %s.\n", localdate(time(NULL)));
return 0;
}
You will want to supply the timestamp (time(NULL)) to the function. If you ever happen to use some date/time function twice, you want to obtain the time once, and use the same value everywhere; otherwise you may see a date change between the two uses. It really does happen, you know.
Each call to localdate() will overwrite the previous value. This means it is not re-entrant; if you use threads, two threads calling it at the same time will get a garbled value.
There are two options to make functions like this re-entrant: Either by letting the caller specify the buffer:
char *localdate_r(time_t when, char **bufptr, size_t *sizeptr)
{
struct tm when_tm;
size_t size;
char *buffer;
if (&when_tm != localtime_r(&when, &when_tm))
return NULL;
if (!bufptr || !*bufptr) {
if (sizeptr && *sizeptr > 11)
size = *sizeptr;
else
size = 12;
buffer = malloc(size);
if (!buffer)
return NULL;
} else
if (sizeptr && *sizeptr > 11) {
buffer = *bufptr;
size = *sizeptr;
} else {
size = 12;
buffer = realloc(*bufptr, size);
if (!buffer)
return NULL;
}
if (bufptr)
*bufptr = buffer;
if (sizeptr)
*sizeptr = size;
if (strftime(buffer, size, "%Y-%m-%d", &when_tm) >= size)
return NULL;
return buffer;
}
int main(void)
{
char *buffer = NULL; /* Must be initialized to NULL */
size_t length = 0; /* Must be initialized to a sane value or zero */
printf("Today is %s.\n", localdate_r(time(NULL), &buffer, &size));
/* Discard buffer if used */
if (buffer)
free(buffer);
buffer = NULL;
length = 0;
return 0;
}
The first approach is suitable only for single-threaded processes. The second approach is usually the simplest to implement. The last approach is the most flexible, and has been found very useful: compare C99 getline() to the old fgets() for example.
Last edited by Nominal Animal; 06-08-2012 at 07:45 AM.
Reason: URL end tags
Because datebuf is marked static, it exists in the data segment instead of stack; it always exists, but is accessible only within the function itself. It is basically a global variable, but only known to the function body.
You can use the function for example thus:
Code:
int main(void)
{
printf("Today is %s.\n", localdate(time(NULL)));
return 0;
}
You will want to supply the timestamp (time(NULL)) to the function. If you ever happen to use some date/time function twice, you want to obtain the time once, and use the same value everywhere; otherwise you may see a date change between the two uses. It really does happen, you know.
Each call to localdate() will overwrite the previous value. This means it is not re-entrant; if you use threads, two threads calling it at the same time will get a garbled value.
There are two options to make functions like this re-entrant: Either by letting the caller specify the buffer:
char *localdate_r(time_t when, char **bufptr, size_t *sizeptr)
{
struct tm when_tm;
size_t size;
char *buffer;
if (&when_tm != localtime_r(&when, &when_tm))
return NULL;
if (!bufptr || !*bufptr) {
if (sizeptr && *sizeptr > 11)
size = *sizeptr;
else
size = 12;
buffer = malloc(size);
if (!buffer)
return NULL;
} else
if (sizeptr && *sizeptr > 11) {
buffer = *bufptr;
size = *sizeptr;
} else {
size = 12;
buffer = realloc(*bufptr, size);
if (!buffer)
return NULL;
}
if (bufptr)
*bufptr = buffer;
if (sizeptr)
*sizeptr = size;
if (strftime(buffer, size, "%Y-%m-%d", &when_tm) >= size)
return NULL;
return buffer;
}
int main(void)
{
char *buffer = NULL; /* Must be initialized to NULL */
size_t length = 0; /* Must be initialized to a sane value or zero */
printf("Today is %s.\n", localdate_r(time(NULL), &buffer, &size));
/* Discard buffer if used */
if (buffer)
free(buffer);
buffer = NULL;
length = 0;
return 0;
}
The first approach is suitable only for single-threaded processes. The second approach is usually the simplest to implement. The last approach is the most flexible, and has been found very useful: compare C99 [URL=http://www.kernel.org/doc/man-pages/online/pages/man3/getline.3.html]getline()[/FONT] to the old [URL=http://www.kernel.org/doc/man-pages/online/pages/man3/fgets.3.html]fgets()[/FONT] for example.
Thanks very much to you all. I'd learn alot from this thread and wiped off my curiosity about return value.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.