函数接口
#include<unistd.h>
ssize_t read(int fd, void *buf, size_t nbytes);
ssize_t write(int fd, const void *buf, size_t nbytes);
read使用:
- read成功,返回实际读取到的字节数(可能小于指定的),失败返回-1;
- 读普通文件时,若已到达文件尾端,则返回0;
- 读终端设备时,通常一次最多读一行
- 从网络读取时,网络的缓冲机制可能使返回值小于要求读取字节数。
- 从管道或FIFO读时,若管道包含字节数小于所要求读取的,read只返回可读的字节数
write使用:
- 返回值通常与参数nbytes相同,否则表示出错。出错原因之一是磁盘满了,或超出给定进程文件长度限制
- 普通文件的写从文件起始处开始,O_APPEND则从文件末尾开始,写成功则偏移量增加写入的字节数。
测试代码:
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
//#define rw
int main()
{
#ifdef rw
int fd = open("readwrite.txt", O_RDWR |O_CREAT, 0600);
#else
int fd = open("readwrite.txt", O_WRONLY |O_CREAT, 0600);
#endif
if (fd < 0)
{
printf("open file error\n");
return -1;
}
// write
char buf[64];
snprintf(buf, sizeof(buf), "hello world.");
printf("buf:%s\n", buf);
if (write(fd, buf, strlen(buf)) != strlen(buf))
{
printf("write file error\n");
close(fd);
return -1;
}
int pos = lseek(fd, 0, SEEK_CUR);
printf("curr pos:%d\n", pos);
#ifndef rw
close(fd);
#endif
pos = lseek(fd, 0, SEEK_CUR);
printf("curr pos:%d\n", pos);
// read
#ifndef rw
fd = open("readwrite.txt", O_RDONLY |O_CREAT);
#endif
char rdbuf[64];
int len = sizeof(rdbuf);
while(len > 0)
{
int rdbytes = read(fd, rdbuf + sizeof(rdbuf) - len, len);
if (rdbytes <= 0)
break;
len -= rdbytes;
};
printf("read:%s\n", rdbuf);
pos = lseek(fd, 0, SEEK_CUR);
printf("curr pos:%d\n", pos);
close(fd);
}
如果以读写方式打开,读写共用一个偏移量,可以对 #define rw 注释或解注释看看。
参考:
《Unix环境高级编程》3.7-3.8小节