user5688956
user5688956

Reputation:

(efficiently) Writing Identical Data to Multiple Files in C

I am presented with a situation where I must write some string into multiple files. An immediate solution would be to simply loop through each file, writing the same data to each separately. If one wanted to write identical data to multiple file streams concurrently, how would they achieve this efficiently? Though this situation is hypothetical, an example case may be - if one wanted to write to both a FILE* and the stdout stream:

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]);

Though this example shows writing to only 2 target streams, a potential solution should enable writing to as many as 8 file streams. In order to achieve this, is it possible to link files so they point to the same location? In the case that there is no practical method for mirroring file writes, if it is possible to offload file write operations onto a different thread, please don't refrain from posting.

Thanks in advance.

Upvotes: 2

Views: 166

Answers (1)

Andriy Berestovskyy
Andriy Berestovskyy

Reputation: 8534

If one wanted to write identical data to multiple file streams concurrently, how would they achieve this efficiently?

I guess loop is the only option.

In order to achieve this, is it possible to link files so they point to the same location?

If your N files need to be identical, sure you can write just to one and make hard links to this file. Note though that not all the file systems support hard links and any change to one of the files will change all the files at one, because it is basically the same file:

ln orig_file copy1

it is possible to offload file write operations onto a different thread

Sure, threads will help to improve the performance, but your few lines program will become a much longer. Try to increase underneath buffers instead:

man setvbuf

Upvotes: 1

Related Questions