acess() 判断目录是否存在

acess()功能描述:
检查调用进程是否可以对指定的文件执行某种操作。
<pre lang="c" escaped="true">
#include <unistd.h>
int access(const char *pathname, int mode);

</pre>
参数说明:
pathname: 需要测试的文件路径名。
mode: 需要测试的操作模式,可能值是一个或<strong>多个</strong>.
<ol>
<li>R_OK(可读?),</li>
<li> W_OK(可写?), </li>
<li>X_OK(可执行?) </li>
<li>或 F_OK(文件存在?)组合体。 </li>
</ol>


<blockquote>其实在用的最多的主要是利用F_OK来检查目录是否存在。</blockquote>

返回说明:
成功执行时,返回0。失败返回-1,errno被设为以下的某个值
<ol>
<li>EINVAL: 模式值无效 </li>
<li>EACCES: 文件或路径名中包含的目录不可访问 </li>
<li>ELOOP : 解释路径名过程中存在太多的符号连接 </li>
<li>ENAMETOOLONG:路径名太长 </li>
<li>ENOENT: 路径名中的目录不存在或是无效的符号连接 </li>
<li>ENOTDIR: 路径名中当作目录的组件并非目录 </li>
<li>EROFS: 文件系统只读 </li>
<li>EFAULT: 路径名指向可访问的空间外 </li>
<li>EIO: 输入输出错误 </li>
<li>ENOMEM: 不能获取足够的内核内存 </li>
<li>ETXTBSY:对程序写入出错 </li>
</ol>

<pre lang="c" escaped="true" line="1">
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("Usage: ./test filename ");
exit(1);
}

if (access(argv[1], F_OK) == -1) {
puts("File not exists!");
exit(2);
}

if (access(argv[1], R_OK) == -1)
puts("You can't read the file!");
else
if (access(argv[1], R_OK | W_OK) != -1)
puts("You can read and write the file");
else
puts("You can read the file");


exit(0);
}
</pre>

原文地址:https://www.cnblogs.com/liweilijie/p/4984101.html