我有以下代码,我想在其中修改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
请建议任何解决方案。也建议采取任何其他方式。
答案 0 :(得分:2)
对于多行宏,反斜杠必须出现在行的末尾,但是在其中一个反斜杠后面有空格。
宏还存在其他无关的问题:
printf
的多个参数。if
和else
之间)无法正常工作。你需要类似do/while(0)
成语来修复它。要实际重定向标准输出,最好使用freopen
代替。
答案 1 :(得分:2)
@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);
}