How to store the output of multiple commands OR block of code into a single variable. I need to write this into a variable so that it can be used in multiple places.
Following is a dummy program containing a block of code(see comment) which has two printf
statements, I need to store them into a single variable so that it can be used later.
Sample code to show the output format
#include <stdio.h>
int main()
{
int c;
// code block start here
char buffer[128];
for (c = 1; c <= 10; c++)
{
printf("%d",c+2);
if(c%2){
printf("%d\n",c+2);
}
}
//code block ends here
// store the whole output of above code block into variable
//send the data on socket ---this is working ,but need the whole data into the variable
return 0;
}
Above program result like this
-->./a.out
33
455
677
899
101111
12
I tried to use snprintf
to store the output of the two printf into a variable called buffer
but its overwriting the data of last printf.
#include <stdio.h>
int main()
{
int c;
// code block start here
char buffer[128];
for (c = 1; c <= 10; c++)
{
// printf("%d",c+2);
snprintf(buffer, sizeof(buffer), "%d", c+2);
if(c%2){
// printf("%d\n",c+2);
snprintf(buffer, sizeof(buffer), "%d", c+2);
}
}
printf("buffer is %s\n",buffer);
//code block ends here
// store the whole output of above code block into variable
//send the data on socket ---this is working ,but need the whole data into the variable
return 0;
}
Current output:
buffer is 12
Desired output:
buffer is 33\n455\n677\n899\n101111\n12