gpt4 book ai didi

c - 格式化输出 - 相同数据到 C 中的多个文本文件

转载 作者:太空宇宙 更新时间:2023-11-04 02:09:40 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com