標籤:linux c file write read
read code:
[[email protected] 03]# cat ex03-read-01.c
/*檔案ex03-open-03.c,
O_CREAT和O_EXCL的使用*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main(void)
{
int fd = -1,i;
ssize_t size = -1;
/*存放資料的緩衝區*/
char buf[10];
char filename[] = "test.txt";
/*開啟檔案,如果檔案不存在,則報錯*/
fd = open(filename,O_RDONLY);
if(-1 == fd){
/*檔案已經存在*/
printf("Open file %s failure,fd:%d\n",filename,fd);
} else {
/*檔案不存在,建立並開啟*/
printf("Open file %s success,fd:%d\n",filename,fd);
}
/*迴圈讀取資料,直到檔案末尾或者出錯*/
while(size){
/*每次讀取10個位元組資料*/
size = read(fd, buf,10);
if( -1 == size) {
/*讀取資料出錯*/
close(fd);/*關閉檔案*/
printf("read file error occurs\n");
/*返回*/
return -1;
}else{
/*讀取資料成功*/
if(size >0 ){
/*獲得size個位元組資料*/
printf("read %d bytes:",size);
/*列印引號*/
printf("\"");
/*將讀取的資料列印出來*/
for(i = 0;i<size;i++){
printf("%c",*(buf+i));
}
/*列印引號並換行*/
printf("\"\n");
}else{
printf("reach the end of file\n");
}
}
}
return 0;
}
[[email protected] 03]# ./ex03-read-01
Open file test.txt success,fd:3
read 10 bytes:"aaaaaaaaaa"
read 10 bytes:"aaaaaaaaaa"
read 10 bytes:"aaaaaaaaaa"
read 5 bytes:"aaaa
"
reach the end of file
-----write
[[email protected] 03]# cat ex03-write-01.c
/*檔案ex03-write-01.c,
O_CREAT和O_EXCL的使用*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main(void)
{
int fd = -1,i;
ssize_t size = -1;
int input = 0;
/*存放資料的緩衝區*/
char buf[]="quick brown fox jumps over the lazy dog";
char filename[] = "test.txt";
/*開啟檔案,如果檔案不存在,則報錯*/
fd = open(filename,O_RDWR|O_TRUNC);
if(-1 == fd){
/*檔案已經存在*/
printf("Open file %s failure,fd:%d\n",filename,fd);
} else {
/*檔案不存在,建立並開啟*/
printf("Open file %s success,fd:%d\n",filename,fd);
}
/*將資料寫入到檔案test.txt中*/
size = write(fd, buf,strlen(buf));
printf("write %d bytes to file %s\n",size,filename);
/*關閉檔案*/
close(fd);
return 0;
}
[[email protected] 03]# cat text.txt
cat: text.txt: No such file or directory
[[email protected] 03]# cat test.txt
quick brown fox jumps over the lazy dog