C++ 使用 Qt 重命名文件导致 SIGSEGV

标签 c++ qt directory

我只是用一个名为“Sound Juicer”的程序将我所有的 CD 复制到我的电脑上。它工作正常,它为每个艺术家创建一个文件夹,并为每个专辑创建另一个文件夹。当然,在这些文件夹中还有 mp3 文件。

问题是我想要轨道编号、艺术家,然后是轨道标题作为我歌曲的名称。 Sound Juicer 所做的是在代表“磁盘 1 标题”的文件前面添加 d1t。

我是一名程序员,所以我用这个问题来练习一下。这有效:

void MainWindow::rename( const QString & text )
{
    static int _files = 0;

    QDir dir( text );
    QFileInfoList a = dir.entryInfoList( QDir::Files | QDir::Dirs );
    for( int i = 2; i < a.size(); i++ )
    {
        static QDir tmp;

        if( a.at( i ).isDir() )
            rename( a.at( i ).absoluteFilePath() );

        if( a.at( i ).fileName().startsWith( "d1t" ) || a.at( i ).fileName().startsWith( "d2t" ) )
        {
            QString newFile = a.at( i ).fileName().remove(0,3);
            tmp = a.at( i ).dir();

            if( !tmp.rename( a.at( i ).fileName(), newFile ) )
                qDebug() << "Failed";

            _files++;
        }
    }
}

它检查目录,选择第一个文件或目录并检查它是什么。如果它是一个目录,它会调用自己(递归)并再次开始,直到他找到一些文件或不再存在目录。如果找到一个文件,它会重命名它并将文件计数器加 1。

但是,它只是重命名了前 2 或 3 个目录中的所有文件。之后它引起了 SIGSEGV。有谁知道出了什么问题吗?

我的目录示例:

1 Directory ("Sum 41") -> 1 Subdirectory ("All Killer No Filler") -> Files "d1t01. Sum 41 - Introduction to Destruction.mp3" etc. ... 2 Subdirectory ("Blah Blah") -> Files ...

2 Directory ("Shinedown") -> 1 Subdirectory ("Sound of Madness") -> Files d1t01. Shinedown - Devour.mp3 etc...

3 Directory ("Guns N’ Roses") -> Subdirectory ("Blah Blah") -> files ... Subdirectory ("Blah ") -> files ...

最佳答案

使用 static 你试图告诉编译器你只需要整个程序中的一个实例,但你将它放在一个 for 循环中。那不是很干净。在这种情况下,静态是无用的。由于静态初始化困惑问题,静态也会导致问题。因此,如果您真的不需要静态初始化,请将其删除并将其设为局部变量或类变量。

重写您的方法,以便能够更好地阅读它,我看到您递归调用该方法,这可能会导致无限循环。

另一个问题是你的文件变量,它的用途是什么?

void MainWindow::rename( const QString & text ) {
    int files = 0;

    QDir dir(text); // does QDir also accept wrong paths?
    QFileInfoList list = dir.entryInfoList(QDir::Files|QDir::Dirs); // does it return a list in all cases?
    foreach (QFileInfo entry, list) {
        if (entry.isDir()) {
            //is everything always ok when doing this?
            // POTENTIAL infinite loop 
            rename(entry.absoluteFilePath());
        }
        else {
            QString fileName = entry.fileName();
            if(fileName.startsWith("d1t") || fileName.startsWith("d2t")) {
                if (!entry.dir().rename(fileName, fileName.remove(0,3))) qDebug() << "Failed";
                files++;
            }
        }
    }
}

关于C++ 使用 Qt 重命名文件导致 SIGSEGV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19301826/

相关文章:

c# - C++ 等同于 C# 的 Func<T, TResult>

c++ - boost 线程池

c++ - 如何在 C++ 类中拥有指向 C 函数的指针?

qt - 捕获 QML 错误信息

go - filepath.Walk() - 我可以提供关于哪些目录不能行走的规则吗?

c++ - 如何从参数列表中推断出函数对象的返回类型?

c++ - 如何将 Qt 头文件包含到内核中?

c++ - 我如何知道正在调用 QGraphicsItem::paint() 进行打印?

bash - 是否有代表 'that' 目录的 bash 符号?

python-3.x - 在 Python 中正确实现 Shutil.Error