代码示例_文件IO_read / write

read_write


read_write.c

 

 1 #include <sys/types.h>
 2 #include <sys/stat.h>
 3 #include <fcntl.h>
 4 #include <unistd.h>
 5 #include <stdio.h>
 6 #include <string.h>
 7 #include <stdlib.h>
 8 
 9 int main(void)
10 {
11 
12     char buf1[100];
13     char buf2[100];
14 
15     while(1){
16 
17         // 打开/创建
18         int fd = open("./1.text",O_RDWR);
19         if(fd<0){
20             perror("open failed");
21             exit(1);
22         }
23 
24         //
25         bzero(buf1,100);
26         printf("write :\t");
27         fgets(buf1,100,stdin);
28         if(  write(fd,buf1,strlen(buf1))<0  ){
29             perror("write failed");
30             exit(1);
31         }
32 
33         // 关一下,要不然无法读出数据
34         close(fd);
35 
36 
37         // 打开(读模式)    
38         fd = open("./1.text",O_RDWR);
39 
40         //
41         bzero(buf2,100);
42         if(  read(fd,buf2,strlen(buf1))<0  ){
43             perror("read failed");
44             exit(1);
45         }
46 
47         printf("read  :\t%s\n",buf2);
48 
49         // 关闭
50         close(fd);
51 
52         if(strncmp(buf2,"quit",4)==0)
53             break;
54     }
55 
56 
57     return 0 ;
58 }

 

 

测试:


 

 

success  !

 

posted @ 2019-06-24 15:45  panda_w  阅读(577)  评论(0编辑  收藏  举报