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

转自:http://blog.csdn.net/kingjo002/article/details/8442146

复制代码
一、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:对程序写入出错
 
#include <stdio.h>   
#include <stdlib.h>   
#include <unistd.h>   
#include <fcntl.h>   
  
int main()   
{   
    if((access("test.c",F_OK))!=-1)   
    {   
        printf("文件 test.c 存在.\n");   
    }   
    else  
    {   
        printf("test.c 不存在!\n");   
    }   
  
    if(access("test.c",R_OK)!=-1)   
    {   
        printf("test.c 有可读权限\n");   
    }   
    else  
    {   
        printf("test.c 不可读.\n");   
    }   
  
    if(access("test.c",W_OK)!=-1)   
    {   
        printf("test.c 有可写权限\n");   
    }   
    else  
    {   
        printf("test.c 不可写.\n");   
    }   
    if(access("test.c",X_OK)!=-1)   
    {   
        printf("test.c 有可执行权限\n");   
    }   
    else  
    {   
        printf("test.c 不可执行.\n");   
    }   
  
    return 0;   
}  
 
#include <stdio.h>   
#include <time.h>   
int main()   
{   
    time_t now = time(NULL);   
    char buf[25];   
    strftime(buf,24,"%Y%m%d",localtime(&now));   
    printf("%s\n",buf);   
  
    strftime(buf,24,"%Y-%m-%d %H:%M:%S",localtime(&now));   
    printf("%s\n",buf);   
  
    strftime(buf,24,"%y%m%d %H:%M:%S",localtime(&now));   
    printf("%s\n",buf);   
  
    strftime(buf,24,"%y%m%d",localtime(&now));   
    printf("%s\n",buf);   
  
    strftime(buf,24,"%H:%M:%S",localtime(&now));   
    printf("%s\n",buf);   
    return 0;   
}  
复制代码

 

posted @   Sky&Zhang  阅读(28527)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示