read、write函数理解
程序描述:
首先在当前目录下创建一个名为"file"的文件,然后把"hello world"存到file文件中,最后把file的内容读取出来并打印到屏幕上。
#include <unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <stdlib.h>#include <stdio.h>#include <string.h>int main(){ int fd;/*save file descriptor*/ char buf[11]="hello world",buff[11]; fd=open("file",O_CREAT|O_TRUNC|O_RDWR,0644); if(fd<0) { perror("file creation failed"); exit(EXIT_FAILURE); } if(write(fd,buf,11)<0) { perror("file write failed"); exit(EXIT_FAILURE); } close(fd); if((fd=open("file",O_RDONLY))<0) { perror("file open failed"); exit(EXIT_FAILURE); } if(read(fd,buff,11)>0) { printf("%s\n",buff); } close(fd); exit(EXIT_SUCCESS);}[root@localhost test]# gcc -g fdread.c -o fdread[root@localhost test]# ./fdread hello worldhello world