Consider the following example code:
Code:
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <stdio.h>
#include <wchar.h>
int main(void)
{
FILE *handle;
wchar_t *cache_ptr = NULL;
size_t cache_len = 0;
wchar_t line_buffer[1024];
wchar_t *line;
/* Create the memory stream */
handle = open_wmemstream(&cache_ptr, &cache_len);
if (!handle) {
fprintf(stderr, "Cannot create a wide-character memory stream.\n");
return 1;
}
/* Stuff data into the memory stream */
if (fputws(L"First line\nSecond line\nThird line is the last one\n", handle) == -1) {
fprintf(stderr, "Error writing to the wide-character memory stream.\n");
return 1;
}
/* Rewind the memory stream, so we can read from it */
rewind(handle);
/* Your fgetws() function goes here -- this reads each line */
while (1) {
line = fgetws(line_buffer, sizeof line_buffer, handle);
if (!line)
break;
printf("Read %d wide characters\n", (int)wcslen(line));
}
/* Close the handle normally */
if (fclose(handle)) {
fprintf(stderr, "Error closing wide-character memory stream.\n");
return 1;
}
/* Discard the buffer. */
free(cache_ptr);
cache_ptr = NULL;
cache_len = 0;
return 0;
}
It shows how to create a FILE * handle to wide-character in-memory data. Then I stuff wide-character strings into it, the example data I wish to test. Then I rewind() the stream. Now I can use fgetws() to read the data back from the stream.