[C、C++] UNIX 或 Linux環境中,取得檔案資訊

在撰寫C C++ 常常會有需要判斷一個檔案,
目前的狀態,是不是資料夾、檔案類型、檔案模式的狀況。

在需要這些資訊的時候
您就可以使用

#include <sys/stat.h>

stat 這一個Lib。

透過stst structure 及 fstat(), lstat(), and stat(),
這三個function的配合,
就可以取得檔案的類型、檔案的模式等等資訊。
更多的資訊,您可以參考以下的這個連結
http://www.opengroup.org/pubs/online/7908799/xsh/sysstat.h.html

在這邊提供一個判斷一個檔案是否為資料夾的小程式
來供給大家參考。

#include <sys/stat.h> bool isFileSelected(string filename) { struct stat fileState;  if(filename=="") { //No file selected! return false; }  //stat() is define in <sys/stat.h>. if(!stat(filename.c_str(), &fileState)) { if(!S_ISDIR(fileState.st_mode)) { //It's not a directory. return true; } }  return false;}

 

This entry was posted in 程式語言. Bookmark the permalink.

發表迴響

您的電子郵件位址並不會被公開。 必要欄位標記為 *

*

您可以使用這些 HTML 標籤與屬性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>