如何将Qt控制台输出从命令行存储到文本文件中

How to store Qt console output into text file from command line in Ubuntu

本文关键字:存储 文本 文件 命令行 Qt 控制台 输出      更新时间:2023-10-16

我写了一个Qt应用程序,它在Ubuntu后台作为守护程序运行。这个应用程序在随机时间后崩溃,我想看看它崩溃时给出的错误。

我写这个语法是为了看看我是否能在文本中得到它的输出:

dimit@dimit-FX620DX:~$ ./Myapp &> DebugInfo.txt

,但它不会在文本文件中写入任何内容。我写了这个简单的程序来模拟更大的项目

Mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <stdio.h>
#include <iostream>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    std::vector<int> Test;
    Test[-1] = 90;  //in here it gives segmentation fault error and exits the program
}
MainWindow::~MainWindow()
{
    delete ui;
}
下面是我运行这段代码时的终端输出:
dimit@dimit-FX620DX:~/QtProjects/Test/Test-build-desktop-Qt_4_8_1__System__Debug$ ./Myapp  &> DebugInfo.txt
Aborted (core dumped)

我期望在DebugInfo.txt文件中看到"Aborted (core dump)",但没有在其中写入任何内容。我该怎么办?

我在Ubuntu 12.04下使用Qt 4.8

程序不会打印"Aborted (core dumps)"文本,它是在程序终止后由shell 打印的。因此,解决方案很简单,在另一个shell中运行该程序,并将其输出重定向:

sh -c ./Myapp &> DebugInfo.txt

(-c使shell作为命令行执行命令,这是必需的,因为没有它,sh将尝试将./Myapp作为shell脚本运行并失败。)