On Aug 30, 2013, at 3:45 PM, Andreas Pakulat <ap...@gmx.de> wrote:

> Hi,
> 
> On Fri, Aug 30, 2013 at 9:08 PM, Michael Jackson <imikejack...@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

Thanks for the nice explanations. In some places we use FILE*, some iostream, 
some custom file. There are other places that we use the HDF5 library and it is 
"C" based and takes "char*" for all of its "string" type arguments. Was hoping 
for a nice global "search and replace" but I'll have to take it line by line.

Thanks All.
Mike Jackson
_______________________________________________
Interest mailing list
Interest@qt-project.org
http://lists.qt-project.org/mailman/listinfo/interest

Reply via email to