天天看點

函數realpath/mktemp/access/stat以及fsutils工具中的代碼例子

項目見到了realpath和mktemp這兩個函數,記錄一下一點注意事項

一.realpath

1.函數模型

NAME
       realpath - return the canonicalized absolute pathname

SYNOPSIS
       #include <limits.h>
       #include <stdlib.h>

       char *realpath(const char *path, char *resolved_path);

傳回值: 成功則傳回指向resolved_path的指針,失敗傳回NULL,錯誤代碼存于errno
           

2.使用規則

realpath是用來将參數path所指的相對路徑轉換成絕對路徑,然後存于參數resolved_path所指的字元串數組或指針中的一個函數。

如果resolved_path為NULL,則該函數調用malloc配置設定一塊大小為PATH_MAX的記憶體來存放解析出來的絕對路徑,并傳回指向這塊區域的指針。程式員應調用free來手動釋放這塊記憶體。

bool LaFsUtils::realpath(const char* path, std::string& rlt)
{
    char* ret = ::realpath(path, NULL);//use system function
    if(ret)
    {
        rlt.assign(ret);
        delete ret;
        return true;
    }
    return false;
}
           

二.mktemp

1.函數模型

NAME
       mktemp - make a unique temporary filename
SYNOPSIS
       #include <stdlib.h>
       char *mktemp(char *template);
           

功能: mktemp()用來産生唯一的臨時檔案名。參數template所指的檔案名稱字元串中最後六個字元必須是XXXXXX。産生後的檔案名會借字元串指針傳回。

傳回值: 檔案順利打開後,指向該流的檔案指針就會被傳回。如果檔案打開失敗則傳回NULL,并把錯誤代碼存在errno中。

注意:mktemp函數隻是産生一個臨時的檔案名,并不建立檔案
bool create_temp_dir(const char* prefix, std::string& tempdir)
{
    char* tmpl = mktemp(const_cast<char*>(prefix));
    if(!tmpl)
        return false;
    if(mkdir(tmpl, ))
        return false;
    return true;
}
           

三.access

access():判斷是否具有存取檔案的權限

相關函數

stat,open,chmod,chown,setuid,setgid

表頭檔案

定義函數

int access(const char * pathname, int mode);

函數說明

access()會檢查是否可以讀/寫某一已存在的檔案。參數mode有幾種情況組合, R_OK,W_OK,X_OK 和F_OK。R_OK,W_OK與X_OK用來檢查檔案是否具有讀取、寫入和執行的權限。F_OK則是用來判斷該檔案是否存在。由于access()隻作權限的核查,并不理會檔案形态或檔案内容,是以,如果一目錄表示為“可寫入”,表示可以在該目錄中建立新檔案等操作,而非意味此目錄可以被當做檔案處理。例如,你會發現DOS的檔案都具有“可執行”權限,但用execve()執行時則會失敗。

傳回值

若所有欲查核的權限都通過了檢查則傳回0值,表示成功,隻要有一權限被禁止則傳回-1。

錯誤代碼

EACCESS 參數pathname 所指定的檔案不符合所要求測試的權限。

EROFS 欲測試寫入權限的檔案存在于隻讀檔案系統内。

EFAULT 參數pathname指針超出可存取記憶體空間。

EINVAL 參數mode 不正确。

ENAMETOOLONG 參數pathname太長。

ENOTDIR 參數pathname為一目錄。

ENOMEM 核心記憶體不足

ELOOP 參數pathname有過多符号連接配接問題。

EIO I/O 存取錯誤。

附加說明

使用access()作使用者認證方面的判斷要特别小心,例如在access()後再做open()的空檔案可能會造成系統安全上的問題。

範例

#include<unistd.h>
int main()
{
    if (access(“/etc/passwd”,R_OK) = =)
        printf(“/etc/passwd can be read\n”);
}
           
執行
/etc/passwd can be read 
           

四.stat

NAME
       stat - get file status

SYNOPSIS
       #include <sys/stat.h>

       int stat(const char *restrict path, struct stat *restrict buf);


DESCRIPTION
       The stat() function shall obtain information about the named file
       and write it to the area pointed to by the buf argument. The path
       argument points to a pathname naming a  file.   Read,  write,  or
       execute  permission  of the named file is not required. An imple‐
       mentation that provides additional or alternate file access  con‐
       trol  mechanisms  may,  under  implementation-defined conditions,
       cause stat() to fail. In particular,  the  system  may  deny  the
       existence of the file specified by path.

       If  the  named file is a symbolic link, the stat() function shall
       continue pathname resolution using the contents of  the  symbolic
       link,  and  shall  return information pertaining to the resulting
       file if the file exists.

       The buf argument is a pointer to a stat structure, as defined  in
       the  <sys/stat.h>  header,  into which information is placed con‐
       cerning the file.

       The stat() function shall  update  any  time-related  fields  (as
       described in the Base Definitions volume of IEEE Std -,
       Section , File Times Update), before  writing  into  the  stat
       structure.

       Unless   otherwise  specified,  the  structure  members  st_mode,
       st_ino, st_dev, st_uid, st_gid, st_atime, st_ctime, and  st_mtime
       shall  have  meaningful values for all file types defined in this
       volume of IEEE Std - The value of the member  st_nlink
       shall be set to the number of links to the file.

RETURN VALUE
       Upon  successful  completion,   shall be returned. Otherwise, -
       shall be returned and errno set to indicate the error.

ERRORS
       The stat() function shall fail if:

       EACCES Search permission is denied for a component  of  the  path
              prefix.

       EIO    An error occurred while reading from the file system.

       ELOOP  A loop exists in symbolic links encountered during resolu‐
              tion of the path argument.

       ENAMETOOLONG
              The length of the path argument exceeds  {PATH_MAX}  or  a
              pathname component is longer than {NAME_MAX}.

       ENOENT A component of path does not name an existing file or path
              is an empty string.

       ENOTDIR
              A component of the path prefix is not a directory.

       EOVERFLOW
              The file size in bytes or the number of  blocks  allocated
              to  the  file  or  the file serial number cannot be repre‐
              sented correctly in the structure pointed to by buf.


       The stat() function may fail if:

       ELOOP  More than {SYMLOOP_MAX} symbolic  links  were  encountered
              during resolution of the path argument.

       ENAMETOOLONG
              As  a result of encountering a symbolic link in resolution
              of the path argument, the length of the substituted  path‐
              name string exceeded {PATH_MAX}.

       EOVERFLOW
              A  value to be stored would overflow one of the members of
              the stat structure.


       The following sections are informative.

EXAMPLES
   Obtaining File Status Information
       The following example shows how to obtain file status information
       for a file named /home/cnd/mod1. The structure variable buffer is
       defined for the stat structure.


              #include <sys/types.h>
              #include <sys/stat.h>
              #include <fcntl.h>


              struct stat buffer;
              int         status;
              ...
              status = stat("/home/cnd/mod1", &buffer);

   Getting Directory Information
       The following example fragment gets status information  for  each
       entry in a directory. The call to the stat() function stores file
       information in the stat structure  pointed  to  by  statbuf.  The
       lines  that  follow the stat() call format the fields in the stat
       structure for presentation to the user of the program.


              #include <sys/types.h>
              #include <sys/stat.h>
              #include <dirent.h>
              #include <pwd.h>
              #include <grp.h>
              #include <time.h>
              #include <locale.h>
              #include <langinfo.h>
              #include <stdio.h>
              #include <stdint.h>


              struct dirent  *dp;
              struct stat     statbuf;
              struct passwd  *pwd;
              struct group   *grp;
              struct tm      *tm;
              char            datestring[];
              ...
              /* Loop through directory entries. */
              while ((dp = readdir(dir)) != NULL) {


                  /* Get entry's information. */
                  if (stat(dp->d_name, &statbuf) == -)
                      continue;


                  /* Print out type, permissions, and number of links. */
                  printf("%10.10s", sperm (statbuf.st_mode));
                  printf("%4d", statbuf.st_nlink);


                  /* Print out owner's name if it is found using getpwuid(). */
                  if ((pwd = getpwuid(statbuf.st_uid)) != NULL)
                      printf(" %-8.8s", pwd->pw_name);
                  else
                      printf(" %-8d", statbuf.st_uid);


                  /* Print out group name if it is found using getgrgid(). */
                  if ((grp = getgrgid(statbuf.st_gid)) != NULL)
                      printf(" %-8.8s", grp->gr_name);
                  else
                      printf(" %-8d", statbuf.st_gid);


                  /* Print size of file. */
                  printf(" %9jd", (intmax_t)statbuf.st_size);


                  tm = localtime(&statbuf.st_mtime);


                  /* Get localized date string. */
                  strftime(datestring, sizeof(datestring), nl_langinfo(D_T_FMT), tm);


                  printf(" %s %s\n", datestring, dp->d_name);
              }
           

例子

bool LaFsUtils::isfile(const char* path)
{
    struct stat statbuf;
    if(stat(path, &statbuf) == -)
    {
        return false;
    }
    return S_ISREG(statbuf.st_mode);
}
           

關于S_ISREG宏的使用可以參考http://blog.csdn.net/derkampf/article/details/54744984

參考http://blog.sina.com.cn/s/blog_6a1837e90100uh5d.html