一、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:對程式寫入出錯
例如:
C代碼
- #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 <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;}
運行結果如下:
二、如果在C中列印目前時間
下面是一個列印系統目前時間的小例子,函數的文法暫時就不列出了,只是會用這些就差不多了
C代碼
- #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;
- }
#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;}
運行結果: