文件打開創建補充
(1)O_EXCL
O_EXCL和O_CREAT配合使用
若文件不存在則創建文件
若文件存在則返回-1
代碼演示
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
int main()
{int fd;fd=open("./file1",O_RDWR|O_CREAT|O_EXCL,0600);if(fd==-1){printf("file exit\n");}return 0;
}
(2)O_APPEND
每次寫的時候都加到文件尾端,若沒有O_APPEND,則寫入的東西會把原來文件中的數據覆蓋掉
代碼演示
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{int fd;char*buf="i am handsome";//將要寫入文件的內容fd=open("./file1",O_RDWR|O_APPEND);int n_write=write(fd,buf,strlen(buf));printf("write %d\n ",n_write);close(fd);return 0;
}
(3)O_TRUNC
如果這個文件中本來是有內容的,而且為只讀或只寫成功打開,則將其長度截短為0。
代碼演示
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{int fd;char*buf="i am handsome";fd=open("./file1",O_RDWR|O_TRUNC);int n_write=write(fd,buf,strlen(buf));printf("write %d\n ",n_write);close(fd);return 0;}
(4)creat()函數創建文件
int creat(const char *pathname, mode_t mode);
pathname:要創建的文件名(包含路徑,當前路徑)
mode:創建模式 //可讀可寫可執行
文件的返回值也是文件描述符
宏表示 | 數字 和 含義 |
---|---|
S_IRUSR | 4 ------------------可讀 |
S_IWUSR | 2-------------------可寫 |
S_IXUSR | 1----------------可執行 |
S_IRWXU | 7----可讀可寫可執行 |
代碼演示
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{int fd;char*buf="i am handsome";fd=creat("/home/CLC/file1",S_IRWXU);return 0;
}
文件操作原理簡述
文件描述符:
????????1、對于內核而言,所有打開文件都由文件描述符引用。文件描述符是一個非負整數。當打開一個現存文件或者創建一個新文件時,內核向進程返回一個文件描述符。當讀寫一個文件時,用open和creat返回的文件描述符標識該文件,將其作為參數傳遞給read和write.按照慣例,UNIX shel I使用文件描述符0與進程的標準輸入相結合,文件描述符1與標準輸出相結合,文件描述符2與標準錯誤輸出相結合。STDIN _FILENO、STDOUT_FILENO、 STDERR_FILENO這幾個宏代替了0、1、2這幾個魔數,0、1、2是linux系統默認的文件描述符。
????????2、文件描述符,這個數字在一個進程中表示一個特定含義,當我們open一個文件時,操作系統在內存中構建了一些數據結構來表示這個動態文件,然后返回給應用程序一個數字作為文件描述符,這個數字就和我們內存中維護的這個動態文件的這些數據結構綁定上了,以后我們應用程序如果要操作這個動態文件,只需要用這個文件描述符區分。
????????3、文件描述符的作用域就是當前進程,出了這個進程文件描述符就沒有意義了。open函數打開文件,打開成功返回一個文件描述符,打開失敗,返回-1。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <unistd.h>
#include <string.h>#include <stdlib.h>
int main()
{int fd;char readbuf[128];int n_read=read(0,readbuf,5);//從標準輸入讀取5個字節到readbuf中int n_write=write(1,readbuf,strlen(readbuf));//將readbuf中的內容標準輸出printf("done! \n");
}
總結
文件編程步驟:
1、打開或創建文件
2、讀取文件或寫入文件
3、關閉文件