Read()
原型
#include <unistd.h> 这个头文件 不加好像也不报错。
ssize_t read(int fd,void* buf,size_t count);
错误返回-1 成功返回 0; count 不能超过最大值SSIZE_MAX (32,767).见
http://blog.chinaunix.net/uid-26858322-id-3311624.html
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main()
{
int fd = -1;
ssize_t size =-1,i;
char buf[10];
char filename[]= "test.txt";
fd = open(filename,O_RDONLY); // read only
if(-1 == fd)
{
printf("open file failture");
}else
{
printf("Open success");
}
while(size)
{
size = read(fd,buf,10); // read 10 byte;
if(-1 == size)
{
close(fd);
}else
{
if(size > 0)
{
printf("read %d bytes:",size);
printf("\"");
for(i = 0;i<size;i++)
{
printf("%c",*(buf+i));
}
printf("\"\n");
}else
printf("reach the end of the file \n");
}
}
return 0;
}
write()函数
原型
ssize_t write(int fd,const void*buf,size_t count);
注:写操作函数并不能保证将数据写入磁盘中,在异步操作中经常出现,write()将数据写入缓冲区,在合适的时机再由系统写入实际设备。可以调用fsync()函数,显示将输入写入设备。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
// 写入一个test.txt文件
int main()
{
// int open(char* filename,int flag,int mode);
// ssize_t write(int fd,const void* buf,size_t count);
char*filename = "test.txt";
int fd = open(filename,O_RDWR);
if(-1 == fd)
{
printf("open file error");
return -1;
}else
{
char buf[] = "hello world";
size_t rt = write(fd,buf,strlen(buf));
if(rt == -1)
{
printf("write error!");
close(fd);
return -1;
}else
{
printf("write ok!");
}
}
close(fd);
return 0;
}