QtCore vs C++ STL & boost lib (1) IO

copyright (C) qingfeng Xia 2011-2020 CC-BY-NC 4.0

QFile is the class for  everyday File IO, while C++ STL using  stream

===========based class: std::stream =========
<iostream> (qDebug()  or #include <iostream> cin/cout )
<fstream>  (QFile)
<sstream> (QBuffer)
<boost/archive> ( QDataStream for serialization )

===========QIODevice===========
The QIODevice class is the base interface class of all I/O devices in Qt.

#include <QIODevice>

Inherits: QObject.

Inherited by: Q3Socket, Q3SocketDevice,
QAbstractSocket, QBuffer, QFile, QLocalSocket, QNetworkReply,
and QProcess  ( just like bash shell pipe input and output, Python).

 

=========std::cout in Qt============
std::cout can be used in Qt application, so is <stdio.h>
by default,  only stdout/std::cout can be displayed in ‘Application Output’ tab of QtCreator
there may be some place in IDE to configure Terminal for input (std::cin):

—————————-
Solution for Windows.

In the .pro file add:

QT -= core gui
TEMPLATE = app
CONFIG += console

Go to Project -> Run settings, and make sure “Run in Terminal” is checked.
————————

===========================
it is not recommended to mix STL IO and Qt IO,
============================

but if you want: see <How to use a QFile with std::iostream?>
http://stackoverflow.com/questions/5204335/how-to-use-a-qfile-with-stdiostream

I came up with my own solution (which uses the same idea Stephen Chu suggested)

#include <iostream>
#include <fstream>
#include <cstdio>

#include <QtCore>

using namespace std;

void externalLibFunction(istream & input_stream) {
copy(istream_iterator<string>(input_stream),
istream_iterator<string>(),
ostream_iterator<string>(cout, ” “));
}

ifstream QFileToifstream(QFile & file) {
Q_ASSERT(file.isReadable());
return ifstream(::_fdopen(file.handle(), “r”));
}

int main(int argc, char ** argv)
{
QFile file(“a file”);
file.open(QIODevice::WriteOnly);
file.write(QString(“some string”).toLatin1());
file.close();
file.open(QIODevice::ReadOnly);
std::ifstream ifs(QFileToifstream(file));
externalLibFunction(ifs);
}



CC-BY-NC 4.0 licensed free for non-commercial usage
Author: Qingfeng XIA
copyright (C) 2011-2020
http://www.iesensor.com
please keep the original link in your reference.
https://www.iesensor.com/blog/2013/03/06/qtcore-vs-c-stl-boost-lib-1-io/
This entry was posted in Programming. Bookmark the permalink.