c语言read函数 c语言read函数读取文件

C中read()的用法?read()函数的原型是int read(int fd,void *buf,int count); 。它的功能是“从文件说明符fd相关联的文件中读取count个字符,并把这些字符存储到buf所指的缓冲区中 。返回值是操作成功时所读到的字节数,在文件结束时可能少于count个字节;若返回值为-1则说明出错了,返回0则表示到达文件尾端 。例:从文件ABC.txt中读取前100个字节存入数组buffer中——
#include "stdin.h"
#include "io.h"
#include "fcnt1.h"
int main(void){
int fd;
char buffer[100];
if((fd=open("ABC.txt",O_RDONLY))==-1){
【c语言read函数 c语言read函数读取文件】printf("Can't open file.\n");
exit(-1);
}
if(read(fd,buffer,100)!=100)
printf("Possible read error!\n");
}
C语言 write和read语句的基本用法1、函数名: write
表头文件:#includeunistd.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非有效的文件描述词,或该文件已关闭 。
程序例:
#includestdlib.h
#includeunistd.h
#includestdio.h
#includestring.h
#includefcntl.h
#includeerrno.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
表头文件:#includeunistd.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

推荐阅读