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.\n");   
    }   
    else  
    {   
        printf("file mytest.c not exist\n");   
    }   
  
    if(access("mytest.c",R_OK)!=-1)   
    {   
        printf("file test.c have read permission\n");   
    }   
    else  
    {   
        printf("mytest.c cann't read.\n");   
    }   
  
    if(access("mytest.c",W_OK)!=-1)   
    {   
        printf("mytest.c have write permission\n");   
    }   
    else  
    {   
        printf("mytest.c can't wirte.\n");   
    }   
    if(access("mytest.c",X_OK)!=-1)   
    {   
        printf("file mytest.c have executable permissions\n");   
    }   
    else  
    {   
        printf("file mytest.c Not executable.\n");   
    }   
  
    return 0;   
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM