So, I need to strcat pid to some string. I have this
strcat (str,(char*)getpid());
but this doesn't work.
----edit----
ok i understand the downvotes. i was too quick to post a question. and didnt realize pid returns an int and i can't cast an int to char*
itoa doesnt work because it is not standart c.
this is how i did it.
char pid[10];
snprintf(pid, 10,"%d",(int)getpid());
strcat (str, pid);
Instead of using strcat
to build a string, consider using the much more flexible (and efficient!) sprintf
/snprintf
function instead:
char *end = str;
end += sprintf(end, "%s ", "hello!");
end += sprintf(end, "%ld", (long)getpid());
if(bar)
end += sprintf(end, "%x", 0xf00d);
Observe that sprintf
returns the number of characters written, so you can build a string without succumbing to Schlemiel the Painter's algorithm. If you want to ensure that you don't overrun a buffer of fixed size, snprintf
will do this for you (strcat
will just blindly concatenate, and there is no standard way to avoid that).
Note that the pid_t
standard guarantees that there are "one or more programming environments in which the [width] of pid_t
... is no greater than the width of type long
". Therefore, casting pid_t
to long
is safe as long as getconf
says so.
I see several references that mention casting to long, and then using the %ld
format specifier of sprintf: sprintf(str + strlen(str), "%ld", (long) getpid());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With