Wrapper for fopen in Windows and OSes that implement POSIX

This is a wrapper that I wrote for Vrok to make fopen behave sanely and accept UTF8 strings on all systems. The defines FOPEN_RB, FOPEN_WB…etc had to be defined since systems other than Windows do not have a binary switch for fopen. You can add this code to a header and use fopenu instead of fopen, on POSIX systems there will be no overhead for calling fopenu since it’s just a #define.

#include <cstdio>
#if defined(_WIN32) && defined(UNICODE)
#include <winnls.h>
inline FILE *fopenu(const char *path,const char *opt){
    wchar_t wpath[1024];
    wchar_t wopt[8];
    MultiByteToWideChar(CP_UTF8, 0, path, -1, wpath, 1024);
    MultiByteToWideChar(CP_UTF8, 0, opt, -1, wopt, 8);

    return _wfopen(wpath, wopt);
}
#define FOPEN_RB "rb"
#define FOPEN_WB "wb"
#define FOPEN_AB "wb+"
#else
#define fopenu fopen
#define FOPEN_RB "r"
#define FOPEN_WB "w"
#define FOPEN_AB "w+"
#endif
Advertisements

One thought on “Wrapper for fopen in Windows and OSes that implement POSIX

  1. Nice solution!

    By the way, the FOPEN_*B macros shouldn’t be necessary, I think all platforms accept “b” in the mode string, because it was defined in C89 (though most just ignore it).

    Another suggestions: Not sure UNICODE must be defined for _wfopen() to work, but silently falling back to fopen() on Windows if it’s not defined seems very error-prone to me.
    Maybe use sth like “#error Make sure you build with Unicode support” in that case?

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s