PDA

View Full Version : QTextStream, cout & files



cejohnsonsr
4th September 2010, 02:01
I saw an example of how to connect cout to a QTextStream object so that a file could be written to the same way as stdout. I can't remember where I saw the example. Could someone help me out?

I'm guessing whatever the trick is would work for cin as well.

Please & Thank You,

Ed

tbscope
4th September 2010, 07:15
Try:


QTextStream standardOutputStream(stdout);
QTextStream standardInputStream(stdin);


Now standardOutputStream works like cout
And standardInputStream works like cin

cejohnsonsr
4th September 2010, 19:48
I may have asked the question badly. What you showed me will use the QTextStream object to ouptput to stdout (the monitor). What I want is for the output to go to a file.

Here is what I have. I think you'll be able to see what I want to do.



#include <QtCore/QCoreApplication>
#include <QTextStream>
#include <QString>
#include <QFile>

QTextStream cout(stdout, QIODevice::WriteOnly); //Same example showed what these are for.
QTextStream cerr(stderr, QIODevice::WriteOnly); //I haven't figured out how to use them to output to a file

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString str1, str2(" fixPath");
QFile inFile("fixPath.txt"), outFile("fixPath2.txt");


if(inFile.open(QIODevice::ReadOnly) && outFile.open(QIODevice::WriteOnly))
{
QTextStream inFileStream(&inFile);
QTextStream outFileStream(&outFile);
while (not inFileStream.atEnd())
{
str1 = inFileStream.readLine();
if (str1.contains(str2))
{
str1.remove(str2);
outFileStream << str1 << endl;//here is where I'd like to be able to use cout
} //to write to the file instead of the screen
else
outFileStream << str1 << endl;
}
inFile.close();
outFile.close();
}

//return a.exec();
}

cejohnsonsr
4th September 2010, 19:55
I think I might have just solved my own problem. I tried naming the QTextStream object cout instead of outFileStream. Now when I use cout<< the output goes to the file instead of the screen. I'm certain the example I saw was more involved than this. I'm not sure why if it's this simple. Is there a better way to do this?

Thanx,

Ed

wysota
5th September 2010, 14:36
You mean that you want everything that goes to std::cout to really go to a file?

I don't think QTextStream alone can do that. I guess you could dup() (or dup2()) stdout, open QFile on the duplicated descriptor, read data from it as it comes (using signals and slots) and write it all to some file although I wouldn't call that efficient. It would be much easier to use qDebug() instead of cout and use a handler that will write it to a file or simply stream the output directly to QTextStream connected to a file.