1. 程式人生 > >Qt QFile::copy建立檔案問題

Qt QFile::copy建立檔案問題

一 定義

看一下Qt assistant上關於QFile::copy的說明(Qt5.9.2):

bool QFile::copy(const QString &newName)
Copies the file currently specified by fileName() to a file called newName. Returns true if successful; otherwise returns false.
Note that if a file with the name newName already exists, copy() returns false (i.e. QFile will not overwrite it).
The source file is closed before it is copied.

QFile::copy會建立一個檔案,如果newName標識的檔案已存在,則不會重寫它,結果通過返回值標明。

二 問題

最近發現在老專案上出現一個bug:一個ini的配置檔案新增在qrc檔案中,程式碼中通過QFile讀取並copy到快取目錄中,配置檔案內容在UI上顯示並支援增刪改,但在win10上,使用者新增內容項後下次啟動程式發現新新增內容丟失。

最開始一直懷疑是wfopen的問題,後來發現是隻能r不能w, 開啟配置檔案屬性是隻讀的。

也就是說 在win10上QFile::copy建立的檔案屬性預設是隻讀的,如果需要讀寫,可以在之後呼叫QFile::setPermissions函式設定檔案的permissions和ownership