C语言中的Write函数

Python015

C语言中的Write函数,第1张

write()写文件函数

原形:int

write(int

handle,char

*buf,unsigned

len)

用法:write(文件句柄,缓冲区地址,缓冲区字节长度<最大65534>)

功能:将缓冲区的数据写入与handle相联的文件或设备中,handle是从creat、open、dup或dup2调用中得到的文件句柄。对于磁盘或磁盘文件,写操作从当前文件指针处开始,对于用O_APPEND选项打开的文件,写数据之前,文件指针指向EOF;对于设备,字节被直接传送到设备中;

返回值:实际写入的字节数(不包括回车符),出错时返回-1。

头文件:io.h

大多数情况下,write成功后返回的写入字节数都等于你传入的长度。

但是如果你要写的长度超过了的文件的最大可能时,比方说,你的磁盘还剩下128个字节,这时你向磁盘上的某个文件一次性写512个字节,返回值就是128,只有前128个字节成功写入。

再比如,你用write写的不是一个普通文件,而是设备文件/socket等,那也可能返回值小于你指定的值,这就可能是具体设备的限制等,比如写入的数量超过了缓冲大小等。

1、函数名: write

表头文件:#include<unistd.h>

定义函数:ssize_t write (int fd,const void * buf,size_t count)

函数说明:write()会把指针buf所指的内存写入count个字节到参数fd所指的文件内。当然,文件读写位置也会随之移动。

返回值:如果顺利write()会返回实际写入的字节数。当有错误发生时则返回-1,错误代码存入errno中。

错误代码:

EINTR 此调用被信号所中断。

EAGAIN 当使用不可阻断I/O 时(O_NONBLOCK),若无数据可读取则返回此值。

EBADF 参数fd非有效的文件描述词,或该文件已关闭。

程序例:

#include<stdlib.h>

#include<unistd.h>

#include<stdio.h>

#include<string.h>

#include<fcntl.h>

#include<errno.h>

intmain(void)

{

inthandle

charstring[40]

intlength,res

/*

Createafilenamed"TEST.$$$"inthecurrentdirectoryandwrite

astringtoit.If"TEST.$$$"alreadyexists,itwillbeoverwritten.

*/

if((handle=open("TEST.$$$",O_WRONLY|O_CREAT|O_TRUNC,

S_IREAD|S_IWRITE))==-1)

{

printf("Erroropeningfile.\n")

exit(1)

}

 

strcpy(string,"Hello,world!\n")

length=strlen(string)

 

if((res=write(handle,string,length))!=length)

{

printf("Errorwritingtothefile.\n")

exit(1)

}

 

printf("Wrote%dbytestothefile.\n",res)

close(handle)

return0

}

 

structxfcb{

charxfcb_flag/*Contains0xfftoindicatexfcb*/

charxfcb_resv[5]/*ReservedforDOS*/

charxfcb_attr/*Searchattribute*/

structfcbxfcb_fcb/*Thestandardfcb*/

}

2、函数名: read

表头文件:#include<unistd.h>

定义函数:ssize_t read(int fd,void * buf ,size_t count)

函数说明:read()会把参数fd 所指的文件传送count个字节到buf指针所指的内存中。若参数count为0,则read为实际读取到的字节数,如果返回0,表示已到达文件尾或是无可读取的数据,此外文件读写位置会随读取到的字节移动。

附加说明:如果顺利read()会返回实际读到的字节数,最好能将返回值与参数count 作比较,若返回的字节数比要求读取的字节数少,则有可能读到了文件尾、从管道(pipe)或终端机读取,或者是read()被信号中断了读取动作。当有错误发生时则返回-1,错误代码存入errno中,而文件读写位置则无法预期。

错误代码:

EINTR 此调用被信号所中断。

EAGAIN 当使用不可阻断I/O 时(O_NONBLOCK),若无数据可读取则返回此值。

EBADF 参数fd 非有效的文件描述词,或该文件已关闭。

程序例:

#include

#include

#include

#include

#include

#include

int main(void)

{

void *buf

int handle, bytes

buf = malloc(10)

/*

Looks for a file in the current directory named TEST.$$$ and attempts

to read 10 bytes from it. To

}

if ((bytes = read(handle, buf, 10)) == -1) {

printf("Read Failed.\n")

exit(1)

}

else {

printf("Read: %d bytes read.\n", bytes)

}

return 0