1

我正在工作的程序生成数据,我使用 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. 
4

1 回答 1

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()!
于 2013-04-12T20:26:29.390 回答