On Tue, Jun 21, 2011 at 10:39 AM, Viet Hung Nguyen <[email protected]>wrote:
> Hi all, I'm trying to write a function for my assigment, that function need
> to print out to both stdout and a file. My C program get user input by
> scanf.
> I intend to write a function like printf but i don't really know how:
>
> I tried this, but it only can work with "pure" string, can't convert %d,
> %.*lf...
>
>> void dupPrint(FILE *fp,char *string)
>> {
>> printf("%s",string);
>> fprintf(fp,"%s",string);
>>
>> return;
>> }
>>
>
>
> I tried dup2 and freopen but they didn't work for me.
>
> #include <stdio.h>
>> #include <unistd.h>
>> #include <fcntl.h>
>>
>> int main()
>> {
>> int file = open("input3.txt", O_APPEND | O_WRONLY);
>> if(file < 0) return 1;
>>
>> if(dup2(file,1) < 0) return 1;
>>
>> printf("Redirect to file!\n");
>> printf("Nhap vao so i : ");
>> // scanf("%d",&i);
>> //printf("%d\n",i);
>>
>>
>> return 0;
>> }
>>
> This dup2() tut only print to file.
>
> I also tried tee, but may be it not work because I have to get input from
> user (if work, it's not "fair" because tee isn't in my program).
>
> Can anyone suggest a solution for my problem.
> Thanks!
> (sorry for my bad English).
>
>
> --
> Thanks & Best regards,
>
> Nguyen Viet Hung (Mr)
>
> Email: [email protected]
>
i think vsnprintf and something like va_list will help you.
void dubPrint(FILE *fp, const char *format, ...)
{
int buf_size = 1024;
char *buf = new char[buf_size];
va_list args;
va_start(args, format);
while (vsnprintf(buf, buf_size, format, args) >= buf_size) {
delete[] buf;
buf_size *= 2;
buf = new char[buf_size];
}
va_end(args);
printf("%s\n", buf);
fprintf(fp, "%s\n", buf);
fflush(fp);
}
_______________________________________________
POST RULES : http://wiki.hanoilug.org/hanoilug:mailing_list_guidelines
_______________________________________________
HanoiLUG mailing lists: http://lists.hanoilug.org/
HanoiLUG wiki: http://wiki.hanoilug.org/
HanoiLUG blog: http://blog.hanoilug.org/