-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.

3
  • 3
    The way to do it is using freopen(): stackoverflow.com/questions/2648315/… Commented Oct 2, 2014 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. Commented Oct 2, 2014 at 10:43
  • 1
    or just redirect stdout to a file (./a.out >oup.txt) Commented Oct 2, 2014 at 10:53

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.