Writing a UTF-8 string to a file with ICU

If you have an ICU Unicode string formed as a NULL terminated UChar array, it is trivial to write it to a file.

In the previous article, Reading a UTF-8 file in C with ICU, I introduced a function which reads the contents of a UTF-8 file in a Unicode string. I'm going to use that function in the following example to obtain a Unicode string.

#include <stdio.h>
#include <stdlib.h>

#include "unicode/ustdio.h"
#include "unicode/uchar.h"

/**
 * Writes the supplied UChar array to a UTF-8 file.
 *
 * @param filename the path to the file to be written
 * @param str pointer to the UChar array to be written
 */
void write_utf8_file(const char* filename, const UChar* str) {
    /* open a UTF-8 file for writing */
    UFILE* f = u_fopen(filename, "w", NULL, "UTF-8");

    /* write Unicode string to file */
    u_fputs(str, f);

    /* close the file resource */
    u_fclose(f);
}

int main() {
    /* read the string and its size */
    long size;
    UChar* str = read_utf8_file("utf8_test.txt", &size);

    /* write the string to a separate file */
    write_utf8_file("utf8_test_out.txt", str);

    /* free the allocated string */
    free(str);

    return 0;
}