-2

My program executes with two arguments (put in argv) like below:

$ myProgram input output

How do I redirect all printf(..) to the output file? I saw some suggestion about using fflush(stdout) but I haven't used it before. Could anyone please show me an example?

unwind
  • 391,730
  • 64
  • 469
  • 606
Toan Le
  • 412
  • 1
  • 6
  • 17
  • 2
    You need to learn about the [input/output part of the C library](http://en.cppreference.com/w/c/io), for example the [`fopen`](http://en.cppreference.com/w/c/io/fopen), [`fprintf`](http://en.cppreference.com/w/c/io/fprintf) and [`fclose`](http://en.cppreference.com/w/c/io/fclose) functions. – Some programmer dude Feb 23 '15 at 09:41
  • 1
    if you want to write in a file I'll suggest you to use fprint of fwrite, if you want redirect an output google PIPE – Engine Feb 23 '15 at 09:41
  • Give us a small code snippet showing what you have tried. – harald Feb 23 '15 at 09:42
  • 1
    Oh, and there's probably *millions* of pages out there where this information can be found, not to mention that any beginners book on C will have at least a chapter devoted to file handling. – Some programmer dude Feb 23 '15 at 09:46

2 Answers2

1

If you are trying to redirect the output of your program then that can be done easily from the command line itself with out adding any additional code to your program. Just modify the command like this.

$ myProgram input output > example.txt

And if you want to append the output to the end of your output file then the command will be like this.

$ myProgram input output >> output

However in both cases nothing will be printed on the screen. The entire output of the program will be written in the file.

Ayan
  • 797
  • 1
  • 11
  • 18
0

You will have to you fprintf() instead of printf

Here is an exmaple

#include <stdio.h>

main()
{
   FILE *fp;
   fp = fopen("/tmp/test.txt", "w+");
   fprintf(fp, "This is testing for fprintf...\n");
   fputs("This is testing for fputs...\n", fp);
   fclose(fp);
}

For more details read This page and this page This code was taken from first link.

Taimour
  • 459
  • 5
  • 21