New Line not being written on file (Qt)
i am keeping a log of activities in my software using qtextedit. later when i want to save it as a text using toPlainText(), the resul开发者_JAVA技巧ting text file is a single line without any line breaks. I start logging by plainText() and add subsequent additions using append().
void rocketscience::saveLog(){
QFile logFile;
QTextStream logOut;
QString logfName;
QSettings prevSet("us","fr");
if (defaultDir.exists(prevSet.value("settings/logPath").toString()))
logfName= QFileDialog::getSaveFileName(this,"Save File",fName,"Text (*.txt");
if (logfName!=NULL){
logFile.setFileName(logfName);
logFile.open(QIODevice::WriteOnly);
logOut.setDevice(&logFile);
logOut<<ui.statusReport->toPlainText();
logFile.close();
}
}
From the QTextStream class reference (that line is a bit hidden):
Note: On Windows, all '\n' characters are written as '\r\n' if QTextStream's device or string is opened using the QIODevice::Text flag.
where '\n' is the UNIX line ending and '\r\n' is the Windows line ending (CR/LF).
Remove the QTextStream initialisation at the start of your method and change the if statement to this:
if (!logfName.isEmpty())
{
logFile.setFileName(logfName);
logFile.open(QIODevice::WriteOnly);
QTextStream logOut(&logFile, QIODevice::Text);
logOut<<ui.statusReport->toPlainText();
logFile.close();
}
Also note how I changed the if condition. logfName is by default set to "", I'm not sure if comparing to NULL will work. You're better off using the QString::isEmpty() function
Probably the file is written using UNIX line endings? You should open the file in text, to get the local (Windows) line-endings:
logFile.open(QIODevice::WriteOnly|QIODevice::Text);
I had the same issue. However, the solution given by @Tim Meyer, did not work for me. In the line:
QTextStream logOut(&logFile, QIODevice::Text);
An error is shown. So, I did the following and worked for QT5.8:
/**
* Method to save a text file.
* @param asFileName: Complete file path, including name and extension.
* @param asText: Text to be written in the file
* @return true if the save was successful, false otherwise.
*/
bool MainWindow::saveFile(QString asFileName, QString asText)
{
QFile file(asFileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)){
QMessageBox::critical(this,"Error","File could not be opened");
return false;
}
QTextStream out(&file);
out << asText;
file.close();
return true;
}
精彩评论