Linux系統調用--access函數詳解
2007-07-30 23:10
【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:對程序寫入出錯
例子:
/* test.c */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("Usage: ./test filename/n");
exit(1);
}
if (access(argv[1], F_OK) == -1) {
puts("File not exists!");
exit(2);
}
if (access(argv[1], R_OK) == -1)
puts("You can't read the file!");
else
if (access(argv[1], R_OK | W_OK) != -1)
puts("You can read and write the file");
else
puts("You can read the file");
exit(0);
文章出處:DIY部落(http://www.diybl.com/course/6_system/linux/Linuxjs/20081012/150297.html)