2.創建文件file2,寫入字符串“ABCDEFGHIJKLMN”;
3.讀取file1中的內容,寫入file2,使file2中的字符串內容爲“abcdefghijklmn ABCDEFGHIJKLMN”
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main()
{
int fp=open("file1",O_RDONLY);
int fq=open("file2",O_RDWR);
char a[15],b[15];
read(fp,a,15);
read(fq,b,15);
lseek(fq,0,SEEK_SET);
write(fq,a,15);
write(fq,b,15);
close(fp);
close(fq);
return 0;
}
所用函數講解:
1.open
功能
打開或創建一個文件或設備
頭文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
函數原型
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
int creat(const char *pathname, mode_t mode);
返回值
成功時返回新文件描述符
否則返回-1
功能
文件訪問模式
取值說明(/usr/include/fcntl.h)
O_RDONLY:只讀形式打開
O_WRONLY:只寫形式打開
O_RDWR:讀寫形式打開
O_APPEND:追加模式打開
O_TRUNC :若文件存在且爲只讀或只寫成功打開,則將長度截爲0
O_CREAT:若文件不存在則創建之
使用此選項時,需同時說明參數mode,說明文件的存取許可權位
O_EXCL:若同時指定O_CREAT,而文件已經存在,則出錯
該參數可測試文件是否存在,如果不存在則創建此文件
creat()函數說明
等價於已參數O_CREAT|O_WRONLY|O_TRUNC執行open()
2.read()
功能
從文件描述符讀取數據
頭文件
#include <unistd.h>
函數原型
ssize_t read(int fd, void *buf, size_t count);
返回值: 讀到的字節數,若已到文件尾爲0,若出錯爲-1
3.write()
功能
將數據寫入文件描述符
頭文件
#include <unistd.h>
函數原型
ssize_t write(int fd, const void *buf, size_t count);
返回值: 若成功爲已寫的字節數,若出錯爲-1
4.lessk()
功能
調節讀寫的偏移量
頭文件
#include <sys/types.h>
#include <unistd.h>
函數原型
off_t lseek(int fildes, off_t offset, int whence);
返回值
成功時返回偏移量位置
否則返回-1
whence說明
SEEK_SET: 從文件頭開始的偏移量
SEEK_CUR: 從當前位置開始加offset後的偏移值
SEEK_END: 從文件末開始加offset後的偏移值