zoukankan      html  css  js  c++  java
  • 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:对程序写入出错
    

    程序实例:

    #include <stdio.h>   
    #include <stdlib.h>   
    #include <unistd.h>   
    #include <fcntl.h>   
      
    int main()   
    {   
        if((access("mytest.c",F_OK))!=-1)   
        {   
            printf("file mytest.c exist.
    ");   
        }   
        else  
        {   
            printf("file mytest.c not exist
    ");   
        }   
      
        if(access("mytest.c",R_OK)!=-1)   
        {   
            printf("file test.c have read permission
    ");   
        }   
        else  
        {   
            printf("mytest.c cann't read.
    ");   
        }   
      
        if(access("mytest.c",W_OK)!=-1)   
        {   
            printf("mytest.c have write permission
    ");   
        }   
        else  
        {   
            printf("mytest.c can't wirte.
    ");   
        }   
        if(access("mytest.c",X_OK)!=-1)   
        {   
            printf("file mytest.c have executable permissions
    ");   
        }   
        else  
        {   
            printf("file mytest.c Not executable.
    ");   
        }   
      
        return 0;   
    }
    
  • 相关阅读:
    POJ 2513 (Trie树+欧拉通路+并查集判断连通)
    归并排序及序列逆序数
    POJ 2442 Sequence (堆+K路归并)
    POJ 2513 (Trie树+欧拉通路+并查集判断连通)
    J2EE概述
    J2EE概述
    J2EE概述
    学习视频资料下载论坛
    J2EE概述
    J2EE概述
  • 原文地址:https://www.cnblogs.com/shenlinken/p/10185043.html
Copyright © 2011-2022 走看看