我遇到了一种情况,我必须将一些字符串写入多个文件。一个直接的解决方案是简单地循环遍历每个文件,将相同的数据分别写入每个文件。如果想同时将相同的数据写入多个文件流,他们将如何有效地实现这一点?虽然这种情况是假设的,但一个示例可能是 - 如果想要同时写入 FILE*
和 stdout
流:
FILE* streams[] = { /* some file streams */ };
/* is there a more efficient or elegant approach? */
int i;
for (i = 0; i < sizeof(streams); i++)
fputs(/* data */, streams[i]);
虽然此示例显示仅写入 2 个目标流,但潜在的解决方案应该能够写入多达 8 个文件流。为了实现这一点,是否可以链接文件使它们指向同一位置?在没有镜像文件写入的实用方法的情况下,如果可以将文件写入操作卸载到不同的线程上,请不要发帖。
提前致谢。
最佳答案
If one wanted to write identical data to multiple file streams concurrently, how would they achieve this efficiently?
我想循环是唯一的选择。
In order to achieve this, is it possible to link files so they point to the same location?
如果您的 N 个文件需要相同,请确保您可以只写入一个文件并建立到该文件的硬链接(hard link)。请注意,并非所有文件系统都支持硬链接(hard link),并且对其中一个文件的任何更改都会同时更改所有文件,因为它基本上是同一个文件:
ln orig_file copy1
it is possible to offload file write operations onto a different thread
当然,线程将有助于提高性能,但您的几行程序将变得更长。尝试增加底层缓冲区:
man setvbuf
关于c - (高效)在 C 中将相同的数据写入多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43886214/