Question

I wrote a program where i stores list of filenames in a structure which i have to print it in a file.The type of filenames are in LPCWSTR and am stucking with problems that only the address of filename is printed if using ofstream class.I also tried with wofstream but it results in "Access Violation at reading Location".I Searched sites to alleviate this problem but can't able to got a proper solution.Many recommended to try with wctombs function but i can't understand how it is helpful to print a LPCWSTR to a file.Please help me to alleviate this.

My code is like this,

 ofstream out;
 out.open("List.txt",ios::out | ios::app);
  for(int i=0;i<disks[data]->filesSize;i++)
                    {
                        //printf("\n%ws",disks[data]->lFiles[i].FileName);
                        //wstring ws = disks[data]->fFiles[i].FileName;
                        out <<disks[data]->fFiles[i].FileName << "\n";
                    }
                    out.close();
Was it helpful?

Solution

If you do want to convert then this should work (I couldn't get wcstombs working):

#include <fstream>
#include <string>
#include <windows.h>

int main()
{
    std::fstream File("File.txt", std::ios::out);

    if (File.is_open())
    {
        std::wstring str = L"русский консоли";

        std::string result = std::string();
        result.resize(WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, NULL, 0, 0, 0));
        char* ptr = &result[0];
        WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, ptr, result.size(), 0, 0);
        File << result;
    }
}

Using raw strings (because a comment complained about my use of std::wstring):

#include <fstream>
#include <windows.h>

int main()
{
    std::fstream File("File.txt", std::ios::out);

    if (File.is_open())
    {
        LPCWSTR wstr = L"русский консоли";
        LPCSTR result = NULL;

        int len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, 0, 0);

        if (len > 0)
        {
            result = new char[len + 1];
            if (result)
            {
                int resLen = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, &result[0], len, 0, 0);

                if (resLen == len)
                {
                    File.write(result, len);
                }

                delete[] result;
            }
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top