How to write only new text to a text file

时间:2016-11-09 10:41:25

标签: c++ qt

I'm tring to write a C++ application that will only write new text that that is not already contained in a text file, but so far I can't get my implementation won't work. Text is written into the text file even where the text is already contained.

What could I be doing wrong?

The following is my implementation so far.

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";

    }
}

1 个答案:

答案 0 :(得分:2)

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

  

将迭代器推进到下一个条目,并返回文件路径   这个新条目。如果hasNext()返回false,则此函数执行   没有,并返回一个空的QString。

     

您可以调用fileName()或filePath()来获取当前条目文件   name或path,或fileInfo()来获取当前条目的QFileInfo。