Read Unicode UTF-8 file into wstring

前端 未结 6 1760
无人及你
无人及你 2020-11-30 00:26

How can I read a Unicode (UTF-8) file into wstring(s) on the Windows platform?

6条回答
  •  爱一瞬间的悲伤
    2020-11-30 01:16

    Here's a platform-specific function for Windows only:

    size_t GetSizeOfFile(const std::wstring& path)
    {
        struct _stat fileinfo;
        _wstat(path.c_str(), &fileinfo);
        return fileinfo.st_size;
    }
    
    std::wstring LoadUtf8FileToString(const std::wstring& filename)
    {
        std::wstring buffer;            // stores file contents
        FILE* f = _wfopen(filename.c_str(), L"rtS, ccs=UTF-8");
    
        // Failed to open file
        if (f == NULL)
        {
            // ...handle some error...
            return buffer;
        }
    
        size_t filesize = GetSizeOfFile(filename);
    
        // Read entire file contents in to memory
        if (filesize > 0)
        {
            buffer.resize(filesize);
            size_t wchars_read = fread(&(buffer.front()), sizeof(wchar_t), filesize, f);
            buffer.resize(wchars_read);
            buffer.shrink_to_fit();
        }
    
        fclose(f);
    
        return buffer;
    }
    

    Use like so:

    std::wstring mytext = LoadUtf8FileToString(L"C:\\MyUtf8File.txt");
    

    Note the entire file is loaded in to memory, so you might not want to use it for very large files.

提交回复
热议问题