天天看点

函数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