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,有下列两种性质。
随机推荐
- Ceph的工作原理及流程
本文将对Ceph的工作原理和若干关键工作流程进行扼要介绍.如前所述,由于Ceph的功能实现本质上依托于RADOS,因而,此处的介绍事实上也是针对RADOS进行.对于上层的部分,特别是RADOS GW和 ...
- django Chinese
http://usyiyi.cn/translate/django_182/contents.html
- Rhythmk 一步一步学 JAVA (19) JAVA IO 文件常用操作
package com.rhythmk.filedemo; import java.io.BufferedReader; import java.io.File; import java.io.Fil ...
- leetcode189
public class Solution { public void reverse(int[] nums, int start, int end) { while (start < end) ...
- Linux 如何杀死僵尸进程
问题描述: shell > top top - :: up days, :, user, load average: 0.23, 0.81, 1.07 Tasks: total, running ...
- 1.Hadoop集群搭建之Linux主机环境准备
Hadoop集群搭建之Linux主机环境 创建虚拟机包含1个主节点master,2个从节点slave1,slave2 虚拟机网络连接模式为host-only(非虚拟机环境可跳过) 集群规划如下表: 主 ...
- [iOS]UIScrollView嵌套内容在左右拨动的时候自动被顶上问题
遇到的问题是这样的: 适配6+没问题,但是5s就出问题.我UIScrollView嵌套了左侧UIScrollView,右侧UITableView,左右拨动切换,结果5s下拨动之后两边的View都会自动 ...
- com.mysql.jdbc.exceptions.jdbc4.CommunicationsException/com.atomikos.datasource.ResourceException异常解决
tomcat+mysql部署,每天早晨第一次访问web项目,出现mysql的连接timeout异常:com.mysql.jdbc.exceptions.jdbc4.CommunicationsExce ...
- ubuntu系统中出现mysql数据库无法启动报错2002该怎么处理,具体报错信息如正文所示
python@ubuntu:~$ mysql -uroot -pmysqlmysql: [Warning] Using a password on the command line interface ...
- java web 读取配置文件两种方法
package com.tsinghua.getDataBaseConn; import java.io.IOException;import java.io.InputStream;import j ...