1

案子

  1. 我的 Qt 应用程序通过 QFile 创建一个文件
  2. 我打算用dll来读取这个文件

症状

  • dll 不能使用它,因为它被QAppilcation占用了

试图

  1. 我尝试使用 file.close() 来释放文件,但不起作用;
  2. 我尝试了其他应用程序来读取这个文件,与被占用的症状相同,这意味着 dll 很好。

那么,我该怎么做才能释放一个已经被 QFile 创建和关闭的文件呢?

释放 Qt 文件

    void MainWindow::creatFile(){
       QFile file("1.dat");
       if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
           return ;

       if(!file.exists())
           return;

       QTextStream out(&file);
       out << "test" <<endl;

       out.flush();
       file.close(); // .~QFile() is not needed at all.
       return;
   }

将 QString 转换为字符(Fortran)

typedef void (* myfun)(char string[255]); //How Qt pass character to Fortran dll

//QString-> std::string -> char* 
std::string fileName_std = fileName.replace("/","\\").toStdString();
const char* fileName_cstr = fileName_std.c_str();

char fileName_For90[255];
int length = sizeof(fileName_For90); 

//fill the left nulls of char with blanks which are required in Fortran
strcpy(fileName_For90,fileName_cstr);
for(int i = strlen(fileName_For90); i < length; i++){
    fileName_For90[i] = ' '; 
}
4

2 回答 2

0

(This question has answers in the comments and edited into the question. The question has repeated edits and is more like a blog than a question and it is no longer clear what the question was, whereas SO expects a clear question and a clear answer. See Question with no answers, but issue solved in the comments (or extended in chat). I'm putting this community Wiki Answer so that the question is recorded as answered, however I'm finding it hard to extract an answer from all that chat and edit.)

The OP wrote:

Here is what I get during solving:

  1. .close() actually does close the file. And .flush() might be needed as you can find details here QFile::flush() vs QFile::close()
  2. the real problem lies in converting QString to Character in Fortran.
于 2015-01-25T17:04:33.100 回答
0

我建议使用QSaveFile. 我遇到过许多尝试就地创建文件,然后立即引用和使用它的情况,这可能会导致此问题。QSaveFile 在临时空间中创建文件并将其移动到最终目的地。当其他功能或信号进程需要处理文件时,这似乎更具确定性。QFileSystemWatcher 尤其如此。

void MainWindow::createFile(){
   QSaveFile file("1.dat");
   if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
       return ;

   if(!file.exists())
       return;

   QTextStream out(&file);
   out << "test" <<endl;


   file.commit(); // .~QFile() is not needed at all.
   return;

}

于 2017-04-21T18:26:09.350 回答