c++ - 如何只将新文本写入文本文件

标签 c++ qt

我正在尝试编写一个 C++ 应用程序,它只会写入尚未包含在文本文件中的新文本,但到目前为止我无法让我的实现无法正常工作。即使文本已经包含,文本也会写入文本文件。

我做错了什么?

以下是我到目前为止的实现。

void ScanDir::qDirIteratorScanner()
{
    QDirIterator it(this -> basePath, QDir::Files, QDirIterator::Subdirectories);
    while (it.hasNext())
    {
        paths = scanned();

        qDebug() << "Collected : " << paths.size();

        if (!paths.contains(it.next())) {
            WriteToFile writeToFile(basePath, it.next());
            paths << it.next();
        }
        else {
            qDebug() << "Already put : " << it.next();
        }
    }

}  

QStringList ScanDir::scanned()
{
    QStringList paths;

    QFile dataFile(basePath + "data.txt");
    QTextStream in (&dataFile);

    if (dataFile.open(QIODevice::ReadOnly))
    {
        QTextStream in(&dataFile);

        while (!in.atEnd())
        {
            QString line = in.readLine();
            paths << line;
        }

        dataFile.close();
    }

    return paths;
}  

WriteToFile::WriteToFile(QString path, QString data)
{
    path = "E:/Data.txt";
    QFile file(path);
    if ( file.open(QFile::Append) )
    {
        QTextStream stream( &file );
        stream << data << endl;
        qDebug() << "Writting: " << data + "\r\n";

    }
}

最佳答案

每次迭代你应该只调用 it.next() 一次: http://doc.qt.io/qt-5/qdiriterator.html#next

Advances the iterator to the next entry, and returns the file path of this new entry. If hasNext() returns false, this function does nothing, and returns an empty QString.

You can call fileName() or filePath() to get the current entry file name or path, or fileInfo() to get a QFileInfo for the current entry.

关于c++ - 如何只将新文本写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40505005/

相关文章:

c++ - QtSerialPort:在 Windows 7 上重复读取

python - 无法从 PyQt4 导入 QtCore 或 QtGui

c++ - 将 QImage 转换为 YUV420P 像素格式

c++ - 自定义QFileDialog

c++ - 通用 C++ 框架

c++ - 为什么要调用 boost::thread::shared_mutex block 的 lock_upgrade()?

c++ - 如何让这个 Qt 状态机工作?

qt - 如何在 QLIstWidgetItem 中的文本左侧设置图标?

c++ - 为什么原始指针值被覆盖/超出范围

c++ - CUDA 直方图遇到非法内存访问 (77)