read函数:
#include <unistd.h>
ssize_t read(int feledes,void *buff,size_t nbytes);
返回: 读到的字节数,若已到文件末尾则为0,若出错为-1
write函数:
#include <unistd.h>
ssize_t write(int filedes,const void *buff,size_t nbytes);
返回: 若成功为已写的字节数,若出错为-1
对于普通文件,写操作从文件的当前位移量处开始。如果打开时制定了O_APPEND选择项,则在每次写操作之
前将文件位移量设置在文件的当前结尾处。在一次成功写之后,该文件位移量增加实际写的字节数
Example: write.c
/*write.c*/
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAXSIZE
int main(void)
{
int i,fd,size,len;
char *buf="Hello! I'm writing to this file!";
char buf_r[10];
len = strlen(buf);
buf_r[10] = '\0';
if((fd = open("/tmp/hello.c", O_CREAT | O_TRUNC | O_RDWR,0666 ))<0)
{
perror("open:");
exit(1);
}
else
{
printf("open file:hello.c %d\n",fd);
}
if((size = write( fd, buf, len)) < 0)
{
perror("write:");
exit(1);
}
else
{
printf("Write:%s\n",buf);
}
lseek( fd, 0, SEEK_SET );
if((size = read( fd, buf_r, 10))<0)
{
perror("read:");
exit(1);
}
else
{
printf("read form file:%s\n",buf_r);
}
if( close(fd) < 0 )
{
perror("close:");
exit(1);
}
else
{
printf("Close hello.c\n");
}
exit(0);
}