write函数是C语言函数。
write函数所在的头文件为 <unistd.h>
write有两种用法。一种是:
ssize_twrite(int handle, void *buf, int nbyte);
handle 是
文件描述符;
buf是指定的缓冲区,即
指针,指向一段内存单元;
nbyte是要写入文件指定的字节数;返回值:写入文档的字节数(成功);-1(出错)
write函数把buf中nbyte写入文件描述符handle所指的文档,成功时返回写的字节数,错误时返回-1.
另一种是:write(const char* str,int n)
write("string",strlen("string");表示输出
字符串常量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys\stat.h>
#include <io.h>
#include <string.h>
int
main(
void
)
{
int
*handle;
char
string[40];
int
length, res;
/* Create a file named "TEST.$$$" in the current directory and write a string to it. If "TEST.$$$" already exists, it will be overwritten. */
if
((handle = open(
"TEST.$$$"
, O_WRONLY | O_CREAT | O_TRUNC, S_IREAD | S_IWRITE)) == -1)
{
printf
(
"Error opening file.\n"
);
exit
(1);
}
strcpy
(string,
"Hello, world!\n"
);
length =
strlen
(string);
if
((res = write(handle, string, length)) != length)
{
printf
(
"Error writing to the file.\n"
);
exit
(1);
}
printf
(
"Wrote %d bytes to the file.\n"
, res);
close(handle);
return
0;
}
|
读函数read
ssize_t read(
int
fd,
void
*
buf,size_t nbyte)
read函数是负责从fd中读取内容.
成功时,read返回实际所读的字节数,如果返回的值是0,表示已经读到文件的结束了.
小于0表示出现了错误.
如果错误为EINTR说明读是由中断引起的,
如果是ECONNREST表示网络连接出了问题.
写函数write
ssize_t write(
int
fd,
const
void
*
buf,size_t nbytes)
write函数将buf中的nbytes字节内容写入文件描述符fd.成功时返回写的字节数.失败时返回-1. 并设置errno变量. 在网络程序中,当我们向套接字文件描述符写时有俩种可能.
1)write的返回值大于0,表示写了部分或者是全部的数据.
2)返回的值小于0,此时出现了错误.我们要根据错误类型来处理. 如果错误为EINTR表示在写的时候出现了中断错误.
如果为EPIPE表示网络连接出现了问题(对方已经关闭了连接).
1)write的返回值大于0,表示写了部分或者是全部的数据.
2)返回的值小于0,此时出现了错误.我们要根据错误类型来处理. 如果错误为EINTR表示在写的时候出现了中断错误.
如果为EPIPE表示网络连接出现了问题(对方已经关闭了连接).