简体   繁体   中英

Modification of printf function in c

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.

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, 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM