linux C判断文件是否存在【转】

一、access函数

功能描述: 
检查调用进程是否可以对指定的文件执行某种操作。 
  
用法: 
#include <unistd.h>
#include <fcntl.h>

int access(const char *pathname, int mode);   
  
参数: 
pathname: 需要测试的文件路径名。   
mode: 需要测试的操作模式,可能值是一个或多个R_OK(可读?), W_OK(可写?), X_OK(可执行?) 或 F_OK(文件存在?)组合体。 
  
返回说明: 
成功执行时,返回0。失败返回-1,errno被设为以下的某个值 
EINVAL: 模式值无效   
EACCES: 文件或路径名中包含的目录不可访问 
ELOOP : 解释路径名过程中存在太多的符号连接 
ENAMETOOLONG:路径名太长 
ENOENT:  路径名中的目录不存在或是无效的符号连接 
ENOTDIR: 路径名中当作目录的组件并非目录 
EROFS: 文件系统只读 
EFAULT: 路径名指向可访问的空间外 
EIO:  输入输出错误 
ENOMEM: 不能获取足够的内核内存 
ETXTBSY:对程序写入出错

 

  1. #include <stdio.h>   
  2. #include <stdlib.h>   
  3. #include <unistd.h>   
  4. #include <fcntl.h>   
  5.   
  6. int main()   
  7. {   
  8.     if((access("test.c",F_OK))!=-1)   
  9.     {   
  10.         printf("文件 test.c 存在.\n");   
  11.     }   
  12.     else  
  13.     {   
  14.         printf("test.c 不存在!\n");   
  15.     }   
  16.   
  17.     if(access("test.c",R_OK)!=-1)   
  18.     {   
  19.         printf("test.c 有可读权限\n");   
  20.     }   
  21.     else  
  22.     {   
  23.         printf("test.c 不可读.\n");   
  24.     }   
  25.   
  26.     if(access("test.c",W_OK)!=-1)   
  27.     {   
  28.         printf("test.c 有可写权限\n");   
  29.     }   
  30.     else  
  31.     {   
  32.         printf("test.c 不可写.\n");   
  33.     }   
  34.     if(access("test.c",X_OK)!=-1)   
  35.     {   
  36.         printf("test.c 有可执行权限\n");   
  37.     }   
  38.     else  
  39.     {   
  40.         printf("test.c 不可执行.\n");   
  41.     }   
  42.   
  43.     return 0;   
  44. }  

 

  1. #include <stdio.h>   
  2. #include <time.h>   
  3. int main()   
  4. {   
  5.     time_t now = time(NULL);   
  6.     char buf[25];   
  7.     strftime(buf,24,"%Y%m%d",localtime(&now));   
  8.     printf("%s\n",buf);   
  9.   
  10.     strftime(buf,24,"%Y-%m-%d %H:%M:%S",localtime(&now));   
  11.     printf("%s\n",buf);   
  12.   
  13.     strftime(buf,24,"%y%m%d %H:%M:%S",localtime(&now));   
  14.     printf("%s\n",buf);   
  15.   
  16.     strftime(buf,24,"%y%m%d",localtime(&now));   
  17.     printf("%s\n",buf);   
  18.   
  19.     strftime(buf,24,"%H:%M:%S",localtime(&now));   
  20.     printf("%s\n",buf);   
  21.     return 0;   
  22. }  
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值