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,有下列两种性质。
随机推荐
- 为什么KVM计算机点无故重启?
一.故障1:机器hangs 本地一台cloudstack计算节点无故连不上了,cloudstack也坏了,后查看有一台系统虚拟机在这台计算节点上,导致cs挂了.去找到这台机器后,发现这台机器卡住了,重 ...
- 象棋AI算法(二)
原文大神是用html5+js写的关于象棋AI的博客,里面重点讲了棋子的着法,自己设计的评估函数和简单的Minmax理论,没有具体的讲搜索算法,本文是对原文的学习和分析补充 一,棋子的着法com.byl ...
- pandas 读取excle ,迭代
# -*-coding:utf-8 -*- import pandas as pd xls_file=pd.ExcelFile('D:\python_pro\\address_list.xlsx') ...
- Daemon进程
这又是一个有趣的概念,daemon在英语中是"精灵"的意思,就像我们经常在迪斯尼动画里见到的那些,有些会飞,有些不会,经常围着动画片的主人公转来转去,啰里啰唆地提一些忠告,时不时倒 ...
- 【312】◀▶ arcpy 常用函数说明
其他常用的 ArcPy 函数说明 序号 类名称 功能说明 语法 & 举例 01 RefreshActiveView ====<<<< Description ...
- 深度学习篇——Tensorflow配置(傻瓜安装模式)
前言 如果你是一个完美主义者,那么请绕过此文,请参考<深度学习篇——Tensorflow配置(完美主义模式)> 安装 pip install tensorflow ok,只要不报错,安装就 ...
- 使用AddressSanitizer做内存分析(一)——入门篇
使用AddressSanitizer做内存分析 新建文件mem_leak.cpp,键入代码: #include <iostream> int main() { ]; p = NULL; ; ...
- CG中的类型
[Matrix] 通常像下面这样定义Matrix: int1x1 iMatrix; // integer matrix with 1 row, 1 column int4x1 iMatrix; // ...
- Slim安装以及使用【转】
最近在用backbone.js 做东西,因为牵扯到REST services 所以需要后台支持,此处选择了php.Slim 是php的一个框架. 貌似国内文章对此的介绍比较少,在安装Slim的过程中出 ...
- Ubuntu Server 12.04 LTS搭建SVN服务及修改端口
采用了apache结合svn的方式. 首先安装apache.subversion.svn-apache sudo apt-get install apache2 sudo apt-get instal ...