I have a loop that writes out processed data to a file. The data is contained in a linked list and is written out in a while loop which iterates the list.

My question is, should I open/close the write-out files before/after the while loop as shown below, or should I move the open/close within the loop so each iteration opens and then closes the file rather than keeping the file open for the entire duration of the loop?

The linked list has hundreds of MB of data, potentially several GB. Each iteration writes out a line which isn't much more than 80 characters. This is run on a modern linux system.

EDIT: this is not an embedded/critical system. In the unlikely event the process is interrupted before closing the file, it will be restarted.

```
void msgs_output_to_file(Node *head) {
    Node *l = head;
    MsgType msg_type;

    char line[MAX_LINE_SIZE];

    FILE *file1 = NULL;
    FILE *file2 = NULL;

    file1 = fopen("file1.csv", "w");
    file2 = fopen("file2.csv", "w");

    while (l && l->data) {
        memset(line, 0, (size_t) MAX_LINE_SIZE);
        sprintf_msg(line, l->data);
        line[strlen(line)] = '\n'; // add new line

        msg_type = get_msg_type(l->data);
        switch (msg_type) {
            case TYPE_1:
                fputs(line, file1);
                break;
            case TYPE_2:
                fputs(line, file2);
                break;
            default:
                break;
        }
        l = l->next;
    }
    fclose(file1);
    fclose(file2);
}

```