qt检查文件是否存在于目录中,如果它没有提示用户输入其位置,则将该文件复制到程序工作目录

时间:2015-03-30 10:13:33

标签: c++ macos qt qfile qfiledialog

我有一个程序的工作目录是〜/ Library / Application Support / MyApp,它在这里查看config.cfg和日志文件。该程序需要一个名为MP512-Map.map的映射文件。它在此目录中查找以加载它。

当程序首次在新机器上运行时,可能该文件不在此位置,而是在用户桌面上或在可执行文件分发的.dmg内。我想要一个文件对话框弹出并获取.map文件的位置(如果它尚未存在于工作目录中)然后我希望程序将该文件从该位置复制到工作目录,以便下次运行程序时可以加载.map文件就在那里。

我有以下代码:

 QString path = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation);
    QString desktop = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
    QDir dir(path);
    if (!dir.exists()) {
        dir.mkpath(".");   
    }
    QString MapPath = path+"/MP512-Map.map";
    QFile file(MapPath);
    QFile tempfile;
    if(file.exists()!=true){
        qDebug()<<"MAP FILE NOT FOUND.";
        QString temppath = QFileDialog::getOpenFileName(this,tr("Find Location of MP512-Map file:"),desktop,tr("Map Files (*.map)"));
        tempfile.copy(temppath,path);
        qDebug() << "location" << temppath;
        qDebug() << "destination: " << path;
    }

此后,将读入映射文件。问题在于副本。 该文件未成功复制。

控制台输出显示正确的目录:

location "/Users/Mitch/Desktop/MP512-Map.map"
destination:  "/Users/Mitch/Library/Application Support/AFE-MP-512"

我是否正确实施了复制功能?

1 个答案:

答案 0 :(得分:1)

是的,这个功能实现是正确的。但是时间很少

if(!QFile::copy(temppath, file.fileName()))
    qDebug() << file.errorString();
  1. 复制功能(与存在相同)是静态的,您不需要临时对象 - 临时文件
  2. 最好检查复制/读/写功能是否成功