[英]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
多個參數。 if
和else
之間),它將無法正常工作。 您需要類似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.