我正在使用的程序生成数据,我使用fprintf_s()函数输出到文本文件。
由于某些原因,我需要将“相同”数据打印到不同的文本文件(具有不同的名称),所以我想知道我是否可以通过仅调用一次fprintf_s()或者其他一些方法或函数来完成它们。
为了澄清我的问题,我提供了一个愚蠢的例子:
number = 100; FILE fp1, fp2,
fopen_s(&fp1,"file01.txt","w"); fopen_s(&fp2,"file02.txt","w");
//Instead of doing this
fprintf_s(fp1,"I want to print this number = %d\n", number);
fprintf_s(fp2,"I want to print this number = %d\n", number);
// Can I do something like this...
fprintf_s(fp1,fp2,"I want to print this number = %d\n", number);
// I know the above line doesn't work.
答案 0 :(得分:3)
所以你想要重构,嘿?
int multi_printf_s(FILE **fs, size_t n, const char *fmt, ...)
{
va_list argz;
int ret;
for (size_t i = 0; i < n; i++) {
va_start(argz, fmt);
ret = vfprintf_s(fs[i], fmt, argz);
va_end(argz);
}
return ret;
}
通话:
FILE *f1 = fopen(...); // whatever
FILE *f2 = fopen(...);
FILE *f3 = fopen(...);
FILE *f4 = fopen(...);
FILE *fs[] = { f1, f2, f3, f4 };
multi_printf_s(fs, sizeof(fs) / sizeof(fs[0]), "Print this: %d\n", 42);
// don't forget to fclose()!