You are not logged in.
Right now I have the following code in a C++ project. The purpose is to invoke an external script with the myVar variable as an option.
char str[2000];
memset(str, 0, 2000);
sprintf(str, "sh myScript %i", myVar);
system(str);I am wondering if there is any function that can return a formatted string, instead of outputting it to stdout (like printf), storing it to a C string (like sprintf), or writing it to a file (like fprintf). If there's a function like that (I'll call it xprintf), I could simplify my code into this one line.
system(xprintf("sh myScript %i", myVar));Does anyone know if a function like that exists? If not, does anyone know how I could write the function?
Last edited by tony5429 (2011-11-09 04:40:34)
Offline
Such a function would introduce a memory leak in the program, as the string would be allocated but could never be freed, since no pointer to it would exist.
Offline
Hrm, guess that makes sense. Is there any function that would send it to the shell directly, and then free up that RAM? Something like this?
sysprintf("sh myScript %i", myVar);And if not, does anyone know how I could write that function?
Offline
Rather than write a function, you could do it as a pretty simple (c99) macro:
#define sysprintf(...) do{ char* syscmd = calloc (sizeof (char), 2000); sprintf (syscmd, __VA_ARGS__); system (syscmd); free (syscmd); } while (0)And then call it as such:
sysprintf ("sh myScript %i", myVar);Warning: That's untested, and there is probably a far better way of doing it than by just allocating 2000 chars.
Last edited by Barrucadu (2011-10-15 15:51:55)
Offline
The GNU extension has a (non portable) function that allocates the string depending on how much space it needs. I forgot the name, but I'm sure you can search for it online. Still needs to be de-allocated, of course. ![]()
Offline
Thanks, all for your help, with which I was able to come up with a suitable solution. If anyone finds this page and is looking for the solution, it has been implemented in rev 25 of Yellowcot, available here: http://code.google.com/p/yellowcot/sour … svn25&r=25
Offline
You should at least use vsnprintf() to make sure you don't overflow str. Better yet, use vsaprintf() to allocate the string for you, or vsnprintf(NULL, 0, ...) to determine the needed size of the buffer.
Offline