天天看點

Qt中檔案路徑的三種類型以及擷取辨析filePath()、absoluteFilePath() 與canonicalFilePath() 總結

辨析filePath()、absoluteFilePath() 與canonicalFilePath() 

在使用QFileInfo類擷取檔案屬性時,發現一個檔案的路徑有三個函數,分别為:

1. QString filePath() const:

Returns the file name, including the path (which may be absolute or relative).

2. QString absoluteFilePath() const:

Returns an absolute path including the file name. The absolute path name consists of the full path and the file name. 

This function returns the same as filePath(), unless isRelative() is true. In contrast to canonicalFilePath(), symbolic links or redundant "." or ".." elements are not necessarily removed.

3. QString canonicalFilePath()  const:

Returns the canonical path including the file name, i.e. an absolute path without symbolic links or redundant "." or ".." elements.

絕對路徑與相對路徑

絕對路徑是指檔案在硬碟上真正存在的路徑。例如“bg.jpg”這個圖檔是存放在硬碟的“E:\book\網頁布局代碼\第2章”目錄下,那麼 “bg.jpg”這個圖檔的絕對路徑就是“E:\book\網頁布\代碼\第2章\bg.jpg"。

相對路徑是相對于自己的目标檔案位置。例如假設,“s1.htm” 檔案裡引用了“bg.jpg”圖檔,由于“bg.jpg”圖檔相對于“s1.htm”來說,是在同一個目錄的,那麼要在“s1.htm”檔案裡使用以下代 碼後,隻要這兩個檔案的相對位置沒有變(也就是說還是在同一個目錄内),那麼無論上傳到Web伺服器的哪個位置,在浏覽器裡都能正确地顯示圖檔。

總結

當輸入為絕對路徑時,傳回的都是絕對路徑。

當輸入為相對路徑時:

filePath()傳回的是File構造方法裡的路徑,是什麼就是什麼,不增不減;

absoluteFilePath()傳回的其實是user.dir+filePath()的内容,從上面傳回的結果可以得出。

canonicalFilePath()傳回的就是标準的将符号完全解析的路徑。

繼續閱讀