Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Is it possible to do something like below:
char *arr;
int a=10,b=20;
arr=malloc(desired_size);

set_new_stdout(arr);
printf("%d",(a+b));


in this case i will get arr="20". How to do that?

Best Regards,
Mohibur Rashid

[Moved on behalf of the OP]
sorry,

What I want is

I want to call some functions.

But I am not sure whether they print data on console,

Before those text get printed I ensure those text
[/Moved]
Posted
Updated 21-Jun-11 0:15am
v3
Comments
markkuk 21-Jun-11 5:28am    
Is there any reason why you can't use snprintf() or sprintf()?
Mohibur Rashid 21-Jun-11 5:47am    
you might have noticed in my example i didn't print arr. printing arr is not my goal right now.

I hope someone give me the answer.
markkuk 21-Jun-11 5:56am    
So, what exactly is your goal? snprintf() or sprintf() store the formatted output in a character array, isn't that what you are tring to do?

1 solution

There's no redirection of standard output to array of characters (at least as far as I know). However you may use sprintf function that works exactly as printf but writes to a character array insted of writing to stdout.
You may use a preprocessor macro if you like, but i DON'T recommend it (I'm assuming you are using gcc compiler):
C
#ifdef OUTPUT_TO_CONSOLE
  #define PRINT(fmt, ...) printf(format, ## __VA_ARGS__)
#else
  #define PRINT(fmt, ...) sprintf(arr, format, ## __VA_ARGS__)
#endif

#define SIZE 1024
int main()
{
  char arr[SIZE];

//...
  PRINT(("%d",(a+b));
}
 
Share this answer
 
Comments
CPallini 21-Jun-11 6:51am    
[Moved on behalf of the OP]
I understand your solution. But say, if I call a function whose definition does not belong to me and it print some message like it was suppose to be. In that case i cant prevent from printing.

And I guess there might be a solution to change output port..........
CPallini 21-Jun-11 7:05am    
First: please don't add fake answer again and again. Instead post, as appropriate, updates to your original question or replies to other people answers.
As about 'the function whose definition does not belong to me' you may programmatically redirect the standard output, e.g.:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *outfile = freopen("output.txt", "w", stdout);
printf("hello world.txt");
fclose(outfile);
}
Mohibur Rashid 27-Apr-12 5:16am    
hey it would work, why didn't I saw that before?
CPallini 27-Apr-12 5:22am    
I dont' know...
:-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900