I have a QByteArray
and want to use it like a regular text file. How can I use functions like std::basic_istream::read
on it ?
Asked
Active
Viewed 148 times
0

Ted Lyngmo
- 93,841
- 5
- 60
- 108

Anthony
- 98
- 7
-
1This thread may be useful: https://stackoverflow.com/questions/14086417/how-to-write-custom-input-stream-in-c – m7913d Aug 12 '20 at 13:46
-
That sounds like a lot of work. Is there a particular reason why you don't `std::copy()` or `std::copy_n` from it using its `begin()` (and possibly `end()`) iterator(s)? – Ted Lyngmo Aug 12 '20 at 13:50
-
@TedLyngmo, You mean i copy it into another container ? as what John Park said ? – Anthony Aug 15 '20 at 03:15
-
1Yes, sort of. Since Qt's iterators are STL compatible you can use them as you would use any STL iterator. You can also do `std::string from_byte_array(qt_byte_array.begin(), qt_byte_array.end());` to copy out the data or if you don't want to copy: `std::string_view view_over_byte_array(qt_byte_array.begin(), qt_byte_array.size());` should be fine too. I didn't make an answer out of it since you specifically said that you wanted to use it as a file. – Ted Lyngmo Aug 15 '20 at 06:50
1 Answers
2
QByteArray data type is close to a container, not a stream. You can't handle it like a text file unless you inherit std::streambuf class that handles QByteArray internally.
You can also consider converting std::stringstream to QByteArray if you don't care of performance,
std::stringstream ss;
// write to ss ...
.
.
QByteArray qdata = QByteArray::fromStdString(ss.str());
for read operation,
QByteArray qdata; // consider qdata is already filled with data.
std::stringstream ss(qdata.toStdString());

John Park
- 1,644
- 1
- 12
- 17