标签:
1 #include <unistd.h> 2 #include <sys/types.h> 3 #include <sys/stat.h> 4 #include <fcntl.h> 5 #include <stdlib.h> 6 #include <stdio.h> 7 #include <string.h> 8 void main(void) 9 { 10 int fd,size,len; 11 char *buf="Hello! I‘m writing to this file!"; 12 char buf_r[10]; 13 len = strlen(buf); 14 /*调用open函数,以可读写的方式打开*/ 15 if((fd = open("/tmp/hello.c", O_CREAT | O_TRUNC | O_RDWR, 0600 ))<0) 16 { 17 perror("open ERROR"); 18 exit(1); 19 } 20 else 21 { 22 printf("Open file: hello.c %d\n",fd); 23 /*调用write函数,将buf中的内容写入到打开的文件中*/ 24 if((size = write( fd, buf, len)) < 0) 25 { 26 perror("write ERROR"); 27 exit(1); 28 } 29 else 30 { 31 printf("Write:%s\n",buf); 32 /*调用lsseek函数将文件指针移到文件起始,并读出文件中的10个字节*/ 33 lseek( fd, 0, SEEK_SET); 34 if((size = read(fd, buf_r,10))<0) 35 { 36 perror("read ERROR"); 37 exit(1); 38 } 39 else 40 printf("read form file:%s\n",buf_r); 41 } 42 } 43 if( close(fd) < 0 ) 44 { 45 perror("close:"); 46 exit(1); 47 } 48 else 49 { 50 printf("Close hello.c\n"); 51 exit(0); 52 } 53 }
Open file: hello.c 3
Write:Hello! I‘m writing to this file!
read form file:Hello! I‘m
Close hello.c
close函数:
lseek函数是用于在指定的文件描述符中将文件指针定位到相应的位置。
标签:
原文地址:http://www.cnblogs.com/ht-beyond/p/4304521.html