Linux文件定位读写:
read与write在操作的时候,自动移动读取位置.
lseek改变读写位置.
lseek的函数说明:
off_t lseek(
int fd,//定位文件描述符号
off_t off,//定位位置
int whence//定位参照点:文件开始位置/文件结束位置/文件当前位置
//SEEK_SET SEEK_END SEEK_CUR
);
返回值:返回当前读取位置在文件中的绝对位置.
pread和pwrite函数:
#include<unistd.h>
ssize_t pread(int filedes,void *buf,size_tnbytes,off_t offset);
返回值:读到的字节数,若已到文件末尾则返回0,若出错则返回-1
ssize_t pwrite(int filedes,const void*buf,size_t nbytes,off_t offset);
返回值:若成功则返回已写入的字节数,若出错则返回-1
lseek+write=pwrite
lseek+read=pread
注:pread和pwrite的offset是以SEEK_SET的绝对位置(开始位置)
例子:
Linux中/proc目录中与该进程id相同的文件中有一个mem文件是该进程的内存映射,我们定义一个全局变量并赋值,用该变量的地址作为men文件的偏移量去读取men的内容,是否与该变量的值一样。
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
int a=9999;
void main()
{
int fd,n,data;
char pathname[100];
sprintf(pathname,”/proc/%d/mem”,getpid()); //getpid得到当前进程的id
fd=open(pathname,O_RDONLY);
if(fd== -1)
{
printf(“openerror:%m”);
exit(-1);
}
pread(fd,&data,4,&a); //在文件mem的相对于开始位置//的偏移量为 &a的位置读取
//lseek(fd,&a,SEEK_SET);
//read(fd,&data,4); //等同pread
printf(“%d\n”,data);
close(fd);
}