2

I have a few text files embedded in a .qrc file. However, my back-end project is not based on Qt and a couple of times in the Qt front-end project, I have to call A::read(std::string const& filePath)-like functions that utilize std::ifstream to read the file. Of course, there's no way for std::ifstream to find the file stored in Qt Resource System, so I started thinking about conversion.

Using std::stringstream was the first thing that popped into my head:

std::istringstream iss(QTextStream(&file).readAll().toStdString());
// I didn't find any conversion functions in QTextStream

But I hope that there's something better. (I don't need to preserve unicode.) I will accept even solutions closer to the root of the problem - qrc.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
  • How big are your files? Can you keep the whole text in memory at once? `std::string content = QTextStream(&file).readAll().toStdString()` like a simple approach. – Simon Warta Mar 14 '15 at 11:19
  • @Simon Warta You mean pre-loading? That's not the issue. Problem concerns reading a file from Qt Resource System with standard streams. – LogicStuff Mar 14 '15 at 11:58
  • But why do you need to use the standard streams? Why does it matter how you get from a QRC URL to a file's content? – Simon Warta Mar 14 '15 at 12:01
  • @Simon Warta Well, as mentioned, back-end project does not use Qt and it's API for loading files are functions, that take filepath. So I overloaded these functions to take `std::istringstream`s too. `std::istringstream` can be filled with data read by `QTextStream`. Parameter could be also `std::string`, but it will end up constructing `std::istringstrem` because I need to read formatted text. – LogicStuff Mar 14 '15 at 12:08
  • Then the code you posted is exactly what you need. `iss` is a std::istringstream containing a copy of the content of the file. Now you can read out of `iss`. – Simon Warta Mar 14 '15 at 12:17
  • @Simon Warta Thanks, I wasn't sure. – LogicStuff Mar 14 '15 at 12:25
  • If you are experiencing performance issues in this part – and only then, you can use a binary stream from Qt and construct the std::string directly from a QByteArray because now you convert every text to UTF-16 (in QString) and back into UTF-8 (in std::string). – Simon Warta Mar 14 '15 at 12:37

0 Answers0