Hi everyone. I'm using a third party library in my app written in C, which uses a lot of printf statements. I wanted to redirect that prints to a textEdit on my app. So with the help of others I wrote a redirection function, which redirects stdout to a file and adds text to my textEdit whenever content of file changes. So far so good everything works ok. However at the end external lib call I would like to quit that redirection and delete the file as well, but when I do so I get an error that redirection file does not exist anymore. This would probably mean that signal/slot connection still exists. How can I fix this? Much thanks for help in advance. The code looks like this:
Qt Code:
  1. void MainWindow::RedirectOutput(int type) {
  2. QFileSystemWatcher * watcher = new QFileSystemWatcher(this);
  3. if (type==0) {
  4. // redirect stdout to file
  5. freopen("redirect.txt","w",stdout);
  6.  
  7. // disable buffering
  8. setvbuf(stdout,NULL,_IONBF,0);
  9.  
  10. // check if file changed
  11.  
  12. watcher->addPath("redirect.txt");
  13. connect(watcher,SIGNAL(fileChanged(QString)),this,SLOT(HandleFileChange(QString)));
  14. } else {
  15. // reenable buffering, not really needed
  16. //setvbuf(stdout,NULL,_IOFBF,4000);
  17.  
  18. //return stdout to display
  19. freopen( "CON","w",stdout);
  20. disconnect(watcher,SIGNAL(fileChanged(QString)),this,SLOT(HandleFileChange(QString))); //<doesnt' work
  21. if (QFile::exists("redirect.txt"))
  22. QFile::remove("redirect.txt");
  23. }
  24. }
  25.  
  26. void MainWindow::HandleFileChange(const QString filename){
  27. QFile f(filename);
  28. if (f.open(QIODevice::ReadOnly)) {
  29. //QMessageBox::information(this,"info",QString::number(f.size()));
  30. f.seek(fbytes);
  31. const QByteArray ba = f.readAll();
  32. fbytes += ba.size();
  33. //QMessageBox::information(this,"stdout",filename + " changed:\n\n" + ba);
  34. //cout << qPrintable(ba) << endl;
  35. ui->textEdit->append(qPrintable(ba));
  36. } else {
  37. QMessageBox::critical(this,"stdout","Can't open file");
  38. }
  39. }
To copy to clipboard, switch view to plain text mode