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;   
}  

 


免責聲明!

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



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