read与write
函数原型
ssize_t read(int filedes, void *buf, size_t count);
ssize_t write(int filedes, void* buf, size_t count);
功能
read函数从打开的设备或文件中读取数据。
函数向打开的设备或文件中写数据。
头文件
#include <unistd.h>
返回值
返回值:成功返回写入或读取的字节数count,出错返回-1并设置errno写常规文件时。而write的返回值通常等于请求写的字节数
count,而向终端设备或网络写则不一定。
说明
例:
#include <unistd.h>
#include <stdlib.h> int main(void)
{
char buf[];
int n;
n = read(STDIN_FILENO, buf, );
if (n < ) {
perror("read STDIN_FILENO");
exit();
}
write(STDOUT_FILENO, buf, n);
return ;
}
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h> #define MSG_TRY "try again\n" int main(void)
{
char buf[];
int fd, n;
fd = open("/dev/tty", O_RDONLY|O_NONBLOCK);
if(fd<) {
perror("open /dev/tty");
exit();
}
tryagain:
n = read(fd, buf, );
if (n < ) {
if (errno == EAGAIN) {
sleep();
write(STDOUT_FILENO, MSG_TRY, strlen(MSG_TRY));
goto tryagain;
}
perror("read /dev/tty");
exit();
}
write(STDOUT_FILENO, buf, n);
close(fd);
return ;
}
注:
1.注意返回值类型是ssize_t,表示有符号的size_t,这样既可以返回正的字节数、0(表示到达文件末尾)也可以返回负值-1(表示出错)。
2.使用read,write操作管道,FIFO以及某些设备时,特别是终端,网络和STREAMS,有下列两种性质。
随机推荐
- 升级phpcms的ckeditor编辑器
首先说明一下为什么升级?网上很多人升级成了ueditor,可从fckedotror 到 ckeditor,我个人都是比较喜欢的,特别是开放式的插件方式.另外一个就是至少要懂得升级和插件的开发,这样也能 ...
- 关于linux网络基础记录
1.linux操作系统是一套非常稳定的操作系统,作用永不止于提供网络服务那么简单.(www.Mail.FTP.DNS.DHCP.NAT.Router) 2.对于一个服务器而言,“搭建容易维护难”:维护 ...
- delphi BLE 后台
http://codeverge.com/embarcadero.delphi.ios/
- C++STL:流迭代器
流迭代器是一种迭代器适配器.istream_iterator用于读取输入流,ostream_iterator用于写输出流.这些迭代器将它们所对应的流视为特定类型的元素序列.使用流迭代器时,可以用泛型算 ...
- 【原】Coursera—Andrew Ng机器学习—编程作业 Programming Exercise 4—反向传播神经网络
课程笔记 Coursera—Andrew Ng机器学习—课程笔记 Lecture 9_Neural Networks learning 作业说明 Exercise 4,Week 5,实现反向传播 ba ...
- Spring <context:annotation-config />讲解
在基于主机方式配置Spring的配置文件中,你可能会见到<context:annotation-config />这样一条配置,他的作用是向Spring容器注册AutowiredAnnot ...
- centos7 端口开放
CentOS升级到7之后,发现无法使用iptables控制Linuxs的端口,google之后发现Centos 7使用firewalld代替了原来的iptables.下面记录如何使用firewalld ...
- glTexGen
[glTexGen] Rather than having to explicitly provide a texture coordinate for each vertex, we can use ...
- Cassandra修改集群名称
如果需要在不影响存储数据的情况下,更改cassandra集群名字,可采用如下步骤: 1. 对集群所有节点(for each node)依次连接CQLSH,使用如下命令: UPDATE system. ...
- NoSuchBeanDefinitionException:No qualifying bean of type found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
报错如下: NoSuchBeanDefinitionException:No qualifying bean of type found for dependency: expected at l ...