繁体   English   中英

在C中修改printf函数

[英]Modification of printf function in c

我有以下代码,我想在其中修改printf并写入文件中。 我使用宏相同。

#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");

}

上面的代码给出错误:

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

请提出任何解决方案,也建议采取任何其他方式进行此操作。

对于多行宏,反斜杠必须出现在该行的末尾,但是一个反斜杠之后必须有空格。

宏还有其他不相关的问题:

  • 它不支持printf多个参数。
  • 在某些地方(例如ifelse之间),它将无法正常工作。 您需要类似do/while(0)习惯用法来解决此问题。

要真正标准输出重定向,最好使用freopen来代替。

@ interjay,NPE-简单但出色的答案。 我将使用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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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