http://blog.csdn.net/zjl_1026_2001/article/details/6587320
對於判斷檔案是否存在,每個人有不同的方法。我通常採用兩種方法 : open 和 access ;
這個倆個方法有相似之處,且有不同之處;下面為大家詳細說明他們的不同之處:
open 是開啟,讀寫等操作檔案的一個函數,access就是一個判斷檔案許可權的函數。在linux下,由於檔案有不同的許可權,噹噹前使用者沒有對此檔案的讀許可權的時候,用來判斷檔案是否存在,顯然不合適。而access卻可以做到。
open 的第一個參數是檔案路徑,第二個參數是開啟檔案選項,常用的有O_RDONLY(讀),O_WRONLY(寫),O_RDWR(讀寫),O_CREAT(建立)。 第三個參數通常在建立檔案的時候才使用,給檔案設定許可權使用。
access的第一個參數是檔案路徑,第二個參數是測試的模式。常用的有R_OK:測試讀許可權,W_OK:測試寫入權限,X_OK:測試執行許可權,F_OK:測試檔案是否存在;
我做個例子,寫一個小程式來看兩者的區別。
測試測序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
int main(int argc , char **argv)
{
char path[50];
memset(path,0,50);
sprintf(path,"%s","./test");
int fd;
printf("access function -------------------------/n");
if((fd = access (path,F_OK)) == 0)
printf("[access] file exist!/n");
else
printf("[access] file not exist!!/n");
if((fd = access (path,R_OK)) == 0)
printf("[access] read file ok!/n");
else
printf("[access] read file no!/n");
if((fd = access (path,W_OK)) == 0)
printf("[access] write file ok!/n");
else
printf("[access] write file no!/n");
if((fd = access (path,X_OK)) == 0)
printf("[access] execute file ok!/n");
else
printf("[access] execute file no!/n");
printf("open function -------------------------/n");
if((fd = open (path,O_RDONLY)) == -1)
printf("[open] open no!/n");
else
{
close(fd);
printf("[open] open ok!/n");
}
if((fd = open (path,O_WRONLY)) == -1)
printf("[open] write no!/n");
else
{
close(fd);
printf("[open] write ok!/n");
}
if((fd = open (path,O_RDWR)) == -1)
printf("[open] rdwr no!/n");
else
{
close(fd);
printf("[open] rdwr ok!/n");
}
}
首先我們建立一個普通檔案 test , 修改檔案許可權為0744,修改檔案屬主為root. 我們在普通使用者mpeg4下操作.
[mpeg4@mc2800 file1]$ sudo chown root:root test
[mpeg4@mc2800 file1]$ sudo chmod 0744 test
[mpeg4@mc2800 file1]$ ls -l
total 20
-rwxrwxrwx 1 mpeg4 mpeg4 7157 2009-09-17 09:37 file
-rwxrwxrwx 1 mpeg4 mpeg4 991 2009-09-17 09:44 file.c
-rwxrwxrwx 1 mpeg4 mpeg4 94 2009-09-17 08:56 makefile
-rwxrwxrwx 1 mpeg4 mpeg4 3808 2009-08-20 13:52 records
-rwxr--r-- 1 root root 0 2009-09-17 10:06 test
好了,我們運行我的程式看結果:
[mpeg4@mc2800 file1]$ ./file
access function -------------------------
[access] file exist!
[access] read file ok!
[access] write file no!
[access] execute file no!
open function -------------------------
[open] open ok!
[open] write no!
[open] rdwr no!
很明顯在使用者有讀許可權的情況下,使用那個函數用來判斷檔案是否存在都可以。
現在我們把檔案的許可權改為0740:
sudo chmod 0740 test
再看測試結果:
[mpeg4@mc2800 file1]$ ./file
access function -------------------------
[access] file exist!
[access] read file no!
[access] write file no!
[access] execute file no!
open function -------------------------
[open] open no!
[open] write no!
[open] rdwr no!
可以看到,檔案許可權改變了,就不能用open函數來判斷檔案是否存在了。
我相信很多人都喜歡用open函數來判斷檔案是否存在,當然大家也都知道關於許可權的問題,所以會採用一些必要測措施來控制出錯。但是我建議判斷檔案是否存在最好用access函數。當我們要讀取檔案內容的時候可以使用open來判斷檔案是否存在,就算是因為沒有讀許可權或者檔案真的不存在,都無法實現讀的操作,我們的目的也就達到了