Linux的文件操作有兩種方式:
①Linux系統調用方式,這種方式依賴於Linux系統
②C語言的文件操作,采用C語言的庫函數實現。
以下是Linux系統調用方式:
1. 創建文件
int creat(const char *filename, mode_t mode)
filename:要創建的文件名,包含路徑,缺省時為當前路徑;
mode:創建模式
常見創建模式:
S_IRUSR 可讀 4(直接用數字來表示文件的訪問權限)
S_IWUSR 可寫 2
S_IXUSR 可執行 1
S_IRWXU 可讀、寫、執行 7
實例如下:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void create_file(char *filename){
if(creat(filename,0755)<0){ //指定創建的文件具有地屬性
printf("create file %s failure!\n",filename);
exit(EXIT_FAILURE);
}else{
printf("create file %s success!\n",filename);
}
}
int main(int argc,char *argv[]){
int i;
if(argc<2){
perror("you haven't input the filename,please try again!\n");
exit(EXIT_FAILURE);
}
for(i=1;i<argc;i++){ //可以創建多個文件
create_file(argv[i]);
}
exit(EXIT_SUCCESS);
}
注意:代碼中的系統頭文件都在/usr/include目錄下,這個目錄是gcc定義的系統目錄
訪問權限
每一個文件或是目錄的訪問權限都有三組,每組用三位表示,分別為文件所有者的讀、寫和執行權限;與所有者同組的用戶的讀、寫和執行權限;系統中其他用戶的讀、寫和執行權限。當用ls -l 命令顯示文件或目錄的詳細信息時,最左邊的一列為文件的訪問權限。
例如:$ ls –l sobcrc.tgz
-rw-r--r-- 1 root root 483997 Jul 15 17:31 sobcrc.tgz
注意這裡共有10個位置。第一個字符指定了文件類型,如果第一個字符是橫線,表示是一個非目錄的普通文件,如果是d,表示是一個目錄。r代表只讀,w代表寫,x代表可執行,橫線代表無該項權限。
2. 打開文件和關閉文件
文件描述
在Linux系統中,所有打開的文件都對應一個文件描述符。文件描述符的本質是一個非負整數。當打開一個文件時,該整數由系統來分配。文件描述符的范圍是0~OPEN_MAX。
int open(const char *pathname, int flags)
int open(const char*pathname, int flags, mode_t mode)
pathname:為要打開文件的路徑名,缺省值為當前路徑
flags:當前標志
有:O_RDONLY(只讀方式打開), O_WRONLY(這寫方式打開), O_RDWR(讀寫方式打開), O_APPEND(追加方式打開), O_CREAT(創建一個文件), O_NOBLOCK(非阻塞方式打開)
注意:只有使用O_CREAT標志時,才使用int open(const char*pathname, int flags, mode_t mode)
這時,mode指定創建文件的權限。
int close(int fd) 用於關閉打開的文件,其中fd是已經打開的文件描述符。
例子如下:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc ,char *argv[]){
int fd;
if(argc<2){
puts("please input the open file pathname!\n");
exit(1);
}
//如果flag參數裡有O_CREAT表示,該文件如果不存在,系統則會創建該文件,該文件的權限由第三個參數決定,此處為0755
//如果flah參數裡沒有O_CREAT參數,則第三個參數不起作用.此時,如果要打開的文件不存在,則會報錯.
//所以fd=open(argv[1],O_RDWR),僅僅只是打開指定文件
if((fd=open(argv[1],O_CREAT|O_RDWR,0755))<0){
perror("open file failure!\n");
exit(1);
}else{
printf("open file %d success!\n",fd);
}
close(fd);
exit(0);
}