[Interest] Converting std::string.c_str() code to use QString methods

Andreas Pakulat apaku at gmx.de
Fri Aug 30 21:45:28 CEST 2013


Hi,

On Fri, Aug 30, 2013 at 9:08 PM, Michael Jackson <imikejackson at gmail.com>wrote:

> I have a large code base that we are migrating to more fully utilize Qt
> classes. Many places in the code have lines like the following:
>
> std::string path("/path/to/foo.txt");
> FILE* f = fopen(path.c_str(), "wb");
>
> If the "path" variable is now declared as a QString which QString method
> would be me the equivalent as the "c_str()" of std::string?
>
> Not sure if I should be using "toASCII()" or "data()" or "toUtf8()" or
> what exactly.
>
> Google didn't really give me a definitive answer.
>

In this particular case you want QFile::encode(path).data() to get the
string encoded in a way that fopen can handle - assuming the path actually
comes from the user originally. Otherwise
http://qt-project.org/doc/qt-4.8/qfile.html#encodeName says all hardcoded
paths should be ascii anyway so you could use toAscii().data().

In other places you may need other function, depending on what encoding the
function the char* is passed to expects. For example for the various
print-functions you'd usually use toLocal8Bit().data() to make sure that
the text is printed in the users current locale. Beyond that you'll have to
consult the documentation/implementation of whatever function you want to
pass the string data to wether it expects a certain encoding or requires
ascii etc.

The only thing to watch out for is that toUtf8() gives you a temporary
ByteArray and hence calling data() on it yields a char-pointer to a
temporary memory location. So if you pass this to a function that holds
onto the data beyond its execution you'll need to use something like this
to keep the QByteArray around long enough:

QString path("...");
QByteArray ba = path.toUtf8();
functionThatKeepsReferenceToChar(ba.data());
...

Andreas
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20130830/5abcfe47/attachment.html>


More information about the Interest mailing list