writing multiple lines to a file using multiple fprintf statement vs con-cat multiple lines and then write to a file using one fprintf statement?

Viewed 90

My application (written in C) has to dequeue 500 strings and write them to a text file. I can dequeue every single string and use a separate fprintf statement to write each one to a file, or I can concatenate all the dequeued strings into one string and then write that long concatenated string into a file with single fprintf statement. Which approach is better?

Approach 1:

i = 0;
while (i < 500)
{
    memset(cdr_info, 0, sizeof(cdr_info));
    de_cdrQueue(cdr_info);
    fprintf(fp, "%s\n", cdr_info);
    i++;
}

Approach 2:

char cdr[10000];
i = 0;
while (i < 500)
{
    memset(cdr_info, 0, sizeof(cdr_info));
    de_cdrQueue(cdr_info);
    strcat(cdr,"\n");
    strcat(cdr, cdr_info);
    i++;
}
fprintf(fp, "%s\n", cdr_info);
1 Answers

One of the properties of stdio streams, especially when connected to files, is that they buffer input and output and then write it in large pieces. Thus, unless you've interfered with the buffering of fp, you automatically get I/O behavior similar to approach 2 from approach 1.

Furthermore, you can control the size of the buffer via setvbuf(), so if you want a 10000-byte buffer then you can ensure that, allowing an approach 1 solution with I/O semantics even more similar to your approach 2. Unless you want the concatenated string for more than just printing it, there's pretty much no reason to prefer approach 2 when approach 1 is feasible.

Related