-1

I have the following code in which I want to modify printf and write in a file. I have used macros for the same.

#include<stdio.h>
#define printf(A) {FILE *fp;\  
                   fp=fopen("oup.txt","wb");\
                   fprintf(fp,A);\
                   fclose(fp);}

int main()
{
    int i;
  for(i=0;i<10;i++) 
 printf("Hello\n");

}

Above code gives error:

`this declaration has no storage class or type specifier`at fp=fopen(..) and printf in the code

Please suggest any solution.Also suggest any other way for doing the same.

MS Wachasunder
  • 65
  • 2
  • 10
  • 3
    The way to do it is using `freopen()`: http://stackoverflow.com/questions/2648315/redirecting-stdout-to-a-file-in-c-through-code – NPE Oct 02 '14 at 10:41
  • 1
    Don't do that. Define your own variadic macro `#define myprintf(Fmt,...)` etc.... Don't redefine `printf`, it will confuse any other programmer. – Basile Starynkevitch Oct 02 '14 at 10:43
  • 1
    or just redirect stdout to a file (`./a.out >oup.txt`) – r3mainer Oct 02 '14 at 10:53

2 Answers2

2

For a multi-line macro, the backslash has to appear at the end of the line, but you have spaces after one of the backslashes.

There are also other, unrelated issues with the macro:

  • It won't support multiple arguments to printf.
  • It won't work correctly in some places (such as between if and else). You need something like the do/while(0) idiom to fix that.

To actually redirect standard output, it's better to use freopen instead.

interjay
  • 107,303
  • 21
  • 270
  • 254
2

@interjay, NPE - simple but brilliant answer. I will add an example with freopen:

#include <stdio.h>

int main ()
{
   FILE *fp;

   printf("This text is redirected to stdout\n");

   fp = freopen("file.txt", "w+", stdout);

   printf("This text is redirected to file.txt\n");

   fclose(fp);

   return(0);
}
i alarmed alien
  • 9,412
  • 3
  • 27
  • 40
soerium
  • 573
  • 4
  • 12