pread是一個(gè)函數(shù)文兑,用于帶偏移量地原子的從文件中讀取數(shù)據(jù)盒刚。
帶偏移量地原子的從文件中讀取數(shù)據(jù)
函數(shù)原型
ssize_t pread(intfd, void *buf, size_tcount, off_toffset);
用法
返回值:成功,返回成功讀取數(shù)據(jù)的字節(jié)數(shù)绿贞;失敗因块,返回-1;
參數(shù):
(1) fd:要讀取數(shù)據(jù)的文件描述符
(2) buf:數(shù)據(jù)緩存區(qū)指針籍铁,存放讀取出來的數(shù)據(jù)
(3) count:讀取數(shù)據(jù)的字節(jié)數(shù)
(4) offset:讀取的起始地址的偏移量涡上,讀取地址=文件開始+offset。注意拒名,執(zhí)行后吩愧,文件偏移指針不變
程序?qū)嵗?/p>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void main()
{
int fd;
int count = 128;
int offset = 32;
int ret;
char buf[1024];
char pathname[128] = "/tmp/1.txt";
fd = open( pathname, O_RDONLY);
if((ret =pread(fd,buf,count,offset))==-1)
{
printf("pread error\n");
exit(1);
}
else
{
printf("pread success\n");
printf("the read data is:%s\n", buf);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
部分代碼:
int fd = 0;
//打開文件時(shí),文件的讀寫位置默認(rèn)在文件首部
fd = open("test.dat", O_RDONLY);
if (fd > 0)
{
char caBuf[32] = {'\0'};
int ret = 0;
//將lseek與read合二為一
ret = pread(fd, caBuf, sizeof(caBuf), 5);
if (ret >= 0)
{
printf("%s\n", caBuf);
}
close(fd);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////