1.linux 文件操作

(1)判斷文件是否可以進行某種操作

intaccess(const char *pathname,int mode)

mode可是是R_OK文件可以讀,W_OK文件可以寫,X_OK文件可以執行,F_OK文件存在.這幾個或組合,當測試成功時 ,函數返回0,否則如果有一個條件不符時,返回-1.

如果要獲取其他屬性時可以使用函數stat或者fstat

#include<sys/stat.h>;

#include<unistd.h>;

intstat(const char *file_name,struct stat *buf);

intfstat(int filedes,struct stat *buf);

structstat {

dev_tst_dev; /* 設備 */

ino_tst_ino; /* 節點 */

mode_tst_mode; /* 模式 */

nlink_tst_nlink; /* 硬連接 */

uid_tst_uid; /* 用戶 ID*/

gid_tst_gid; /* ID*/

dev_tst_rdev; /* 設備類型 */

off_tst_off; /* 文件字節數 */

unsignedlong st_blksize; /* 塊大小 */

unsignedlong st_blocks; /* 塊數 */

time_tst_atime; /* 最後一次訪問時間*/

time_tst_mtime; /* 最後一次修改時間*/

time_tst_ctime; /* 最後一次改變時間(指屬性)

};

stat用來判斷沒有打開的文件,fstat用來判斷打開的文件。

S_ISLNK(st_mode):是否是一個連接.S_ISREG是否是一個常規文件.S_ISDIR是否是一個目 錄 S_ISCHR是否是一個字符設備.S_ISBLK是否是一個塊設備 S_ISFIFO是否 是一個 FIFO文 件.S_ISSOCK是否是一個 SOCKET文件.

2)目錄操作

intmkdir(const char *path,mode_t mode);

DIR*opendir(const char *path);

structdirent *readdir(DIR *dir);

voidrewinddir(DIR *dir);

off_ttelldir(DIR *dir);

voidseekdir(DIR *dir,off_t off);

intclosedir(DIR *dir);

structdirent {

longd_ino;

off_td_off;

unsignedshort d_reclen;

chard_name[NAME_MAX+1]; /* 文件名稱*/

mkdir很容易就是我們創建一個目錄,opendir打開一個目錄爲以後讀做準備.readdir讀一 個打開的目錄.rewinddir是用來重讀目錄的和.closedir是關閉 一個目錄.

實例:

#include<unistd.h>

#include<stdio.h>

#include<errno.h>

#include<sys/types.h>

#include<sys/stat.h>

#include<dirent.h>

#include<time.h>

staticint get_file_size_time(const char * filename){

structstat statbuf;

if(stat(filename,&statbuf)==-1){

printf("Getstat on %s\n ERROR",

filename);

return-1;

}

if(S_ISDIR(statbuf.st_mode))

return1;

if(S_ISREG(statbuf.st_mode)){

printf("%ssize:%ld bytes\tmodified at %s",

filename,statbuf.st_size,ctime(&statbuf.st_mtime));

printf("-------------------------------------\n");

intr_ok;

intw_ok;

intx_ok;

intf_ok;

r_ok=access(filename,R_OK);

w_ok=access(filename,W_OK);

x_ok=access(filename,X_OK);

f_ok=access(filename,F_OK);

printf("判斷權限(-1代表否0代表是):讀操作:%d,寫操作:%d,可執行:%d,存在:%d\n",

r_ok,w_ok,x_ok,f_ok);


return0;

}

}


intmain(int argc,char **argv){

DIR* dirp;

structdirent * direntp;

intstats;

if(argc!=2){

printf("usage:%sfilename\n\a",argv[0]);

return1;

}

stats=get_file_size_time(argv[1]);

if(stats==0||stats==-1)

return0;

if((dirp=opendir(argv[1]))==NULL){

printf("opendir %s Error \n",

argv[1]);

return0;

}

while((direntp=readdir(dirp))!=NULL){

if(get_file_size_time(direntp->d_name)==-1)

break;

}

closedir(dirp);

return0;




}


發佈了50 篇原創文章 · 獲贊 7 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章