简体   繁体   English

QT-使用QTextStream将输入的数据写入csv

[英]QT - Writing data input to csv with QTextStream

I have data coming in from an Arduino, which I want to write to a CSV file. 我有来自Arduino的数据,我想将其写入CSV文件。 The problem is the data keeps overwriting the existing line. 问题在于数据不断覆盖现有行。 Here's a sample of the code: 这是代码示例:

QFile data("F:/logdata.csv");


if (data.open(QFile::WriteOnly | QFile::Truncate)) {
 QTextStream out(&data);



 out << hum << "," << temp << "," << gas << '\n';


 }

Are you trying to reopen and append data to the same file? 您是否要重新打开数据并将数据附加到同一文件? In that case you don't want to use the QFile::Truncate flag since it will remove the content in that file. 在那种情况下,您不想使用QFile::Truncate标志,因为它会删除该文件中的内容。

Please see http://doc.qt.io/qt-5/qiodevice.html : 请参阅http://doc.qt.io/qt-5/qiodevice.html

QIODevice::Truncate If possible, the device is truncated before it is opened. QIODevice :: Truncate如果可能,设备在打开之前会被截断。 All earlier contents of the device are lost. 设备的所有早期内容均丢失。

Also as suggested by Ibarros use the QIODevice::Append flag to make sure data is appended. 另外,如Ibarros所建议,请使用QIODevice::Append标志以确保附加了数据。

Update 更新资料

Actually you also don't want to use the QIODevice::WriteOnly flag too, since it will add the truncate flag. 实际上,您也不想使用QIODevice::WriteOnly标志,因为它将添加truncate标志。 You should use QIODevice::ReadWrite instead. 您应该改用QIODevice::ReadWrite

data.open(QIODevice::ReadWrite| QIODevice::Append)

When opening the file, use "QIODevice::Append" flag, so the data you write to it will be appended at the end of the file. 打开文件时,使用“ QIODevice :: Append”标志,因此您写入文件的数据将附加在文件末尾。

Example: 例:

data.open(QFile::WriteOnly | QFile::Truncate |QIODevice::Append)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM