我正在使用的程序生成数据,我使用 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.
最佳答案
所以你想重构,hein?
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()!
关于c - 格式化输出 - 相同数据到 C 中的多个文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15980199/