Qt寫入txt文件方法


void MainWindow::on_saveBtn_clicked()
{
    //本函數只是單獨測試Qt保持為txt文本功能,與本串口程序無任何關系
    QDateTime da_time;
    QString time_str = da_time.currentDateTime().toString("yyyy-MM-dd HH-mm-ss");
//    QString runPath = QCoreApplication::applicationFilePath();
//    QString dirPath = QCoreApplication::applicationDirPath();
//    ui->pathview->setText(runPath); //X:qtworkspace/xxx/xx-desktop-debug/debug/xxx.exe
//    ui->pathview_2->setText(dirPath);//X:qtworkspace/xxx/xx-desktop-debug/debug/
    QDir *DataFile = new QDir;
    bool exist = DataFile->exists("DataFile");
    if(!exist)
    {
        bool isok = DataFile->mkdir("DataFile"); // 新建文件夾
            if(!isok)
                QMessageBox::warning(this,"sdf","can't mkdir",QMessageBox::Yes);
    }
    QString fileName = "DataFile/"+time_str+"datafile.txt";
    QString str = "this is testing for save data to txt file by Qt programming.";
    QFile file(fileName);
    if(!file.open(QIODevice::WriteOnly|QIODevice::Text|QIODevice::Append))
    {
        QMessageBox::warning(this,"sdf","can't open",QMessageBox::Yes);
    }
    QTextStream stream(&file);
    stream<<time_str+":"+str<<"\n";
    file.close();
}

 

代碼比較簡單,就不解釋了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM