QString to wchar_t* conversion
-
Hi,
I am having some confusion regarding conversion from QString to wchar_t* using QString::toWCharArray(wchar_t* inputFileLocation). I am doing this conversion to get location of a file and reading it using C api "_wfopen" and "fread" but it sometimes it is not able to open and read file. Here is a little snipper of my code of what I am doing:QString inFile = "<Some file location is OS dir>"; wchar_t* iFile = new wchar_t[inFile.size()]; inFile.toWCharArray(iFile); FILE* openFile = _wfopen(iFile, L"rb"); if (openFile == NULL) { qDebug() << "Can not open input file"; throw 2; }
Now this behavior was happening very randomly as in sometimes it will open and sometimes it doesn't so I looked online and saw this forum post
conversion issue from QString-wchar_t - stackoverflow
and saw the third post from jake_w that this conversion does not terminate the array with null. I just wanted to confirm whether this conversion terminates the array with null or do I have to do it manually like below:QString inFile = "<Some file location is OS dir>"; wchar_t* iFile = new wchar_t[inFile.size()+1]; inFile.toWCharArray(iFile); iFile[inFile.size()] = '\0'; //Manually terminate array FILE* openFile = _wfopen(iFile, L"rb"); if (openFile == NULL) { qDebug() << "Can not open input file"; throw 2; }
-
@sogo said in QString to wchar_t* conversion:
I just wanted to confirm whether this conversion terminates the array with null or do I have to do it manually like below:
It's mentioned in the documentation: https://doc.qt.io/qt-5/qstring.html#toWCharArray
"Note: This function does not append a null character to the array."... -
@sogo
Given that you are using Qt, why do you want the conversion towchar_t
? You are using it in order to use theFILE
type and do your I/O with calls like_wfopen()
, doubtless under Windows. I cannot see any reason you would want to do that. Given that you are writing a Qt application, you would be much better off using Qt file access functions, for all sorts of reasons.