檔案操作函數中最重要的六個函數分別是
creat,注意沒有e,
open,close,
read,write,
lseek,
這幾個函數分別位於:
create,open,close位於fcntl標頭檔中
read,write,lseek位於unistd標頭檔中
另外還有兩個重要的標頭檔分別為sys/types和sys/stat,分別為系統基礎資料型別 (Elementary Data Type)標頭檔和檔案狀態標頭檔
簡單寫了一個函數
/*檔案操作*/
把一個檔案中的後十個字元列印並且建立一個新檔案將這些字元寫入新檔案中
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
void main(){
int filename;
int i;
char buffer[10];
if((filename = open("/home/yelbosh/desktop/aa.txt",O_RDONLY))<0){
printf("open failed!");
return;
}else{
lseek(filename,-10,SEEK_END);
read(filename,buffer,10);
close(filename);
for(i = 0;i < 10;i++){
printf("%c\n",buffer[i]);
}
}
int cfile;
if((cfile = creat("/home/yelbosh/desktop/tem.txt",664)) < 0)
printf("error");
write(cfile,buffer,10);
close(cfile);
}
結合執行個體探究下各個函數
cfile = creat("/home/yelbosh/desktop/tem.txt",664)
creat函數,
int creat(const char *pathname, mode_t mode);
傳回值:成功返回0,失敗返回-1
(filename = open("/home/yelbosh/desktop/aa.txt",O_RDONLY)
open函數:
int open(const char *pathname, int oflag, … /* mode_t mode */);
傳回值:成功返回的失敗返回-1
第三個參數是可選的,注意第二個參數的含義,是開啟的方式,可取的值為:
O_RDONLY、O_WRONLY、O_RDWR,
O_APPEND 每次寫時都追加到檔案尾端
O_CREAT 若檔案不存在則建立它
O_EXCL 如果同時指定O_CREAT,而檔案已經存在,
則出錯,可測試一個檔案是否已經存在
O_TRUNC 如果檔案存在,而且為唯讀或唯寫成功開啟,則將其長度截短為0
close函數,參數為檔案標識符,成功返回的失敗返回-1
read(filename,buffer,10);
read函數:
ssize_t read(int filedes, void *buff, size_t nbytes);
參數分別是檔案標識符,緩衝區指標,緩衝區大小,傳回值為實際讀取的位元組數
write(cfile,buffer,10);
write函數
ssize_t write(int filedes, const void *buff, size_t nbytes)
參數同read