从文件中读取指定大小的字节函数read()
语法: ssize_t read(int fd,void *buf,int count)
说明:
read函数从指定的打开的文件fd中读取指定大小count的字节到从buf开始的缓冲
区中.
返回值:若读取失败则返回-1.读取成功则返回实际读取到的字节数,有两种情况:[1].读
取到的字节数小于count,这是在读取的文件的总字节数小于count.[2].若读取到的字节
数等于count,则在读取的文件的总字节数不小于count时发生.
注意:读取到的字节存放在buf缓冲区中,必须最后加上一个字节'\0'才能组成一个字符
串.
实例:
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
#define SIZE 1000
int main(int argc,char *argv[])
{
int fd,size;
char buf[1024];
if(argc<2)
{
printf("Usage:%s Filename\n",argv[0]);
exit(1);
}
fd=open(argv[1],O_RDONLY);
if(fd<0)
{
printf("Fail to open file\n");
exit(2);
}
else
{
size=read(fd,buf,SIZE);
if(size<0)
{
printf("Fail to read file\n");
exit(3);
}
else
{
printf("From File %s Read %d bytes\n",argv[1],size);
buf[size]='\0';
printf(buf);
}
close(fd);
}
return 0;
}
转载于:https://blog.51cto.com/huangyandong/677943