目录
2.off_t offset:针对whence位置的偏移数量
四、根据lseek函数的返回值,可以用lseek函数计算出文件内容的大小
例如:有一个file文件,file文件里面的内容是 yyds666!!!
一、read函数使用介绍
#include <unistd.h> // 函数使用的头文件
ssize_t read(int fd, void *buf, size_t count); //函数原型
函数功能介绍:
对函数open打开的文件(文件描述符),把文件里面的数据读取出来。
函数返回值:
成功返回读取的字节数,出错返回-1并设置errno,如果在调read之前已到达文件末尾,则这次read返回0。
函数参数:
inf fd :文件描述符
void *buf :缓冲区,把文件的数据读取到buf
size_t count:需要读取文件的字节数
二、lseek函数使用介绍
#include <sys/types.h>
#include <unistd.h> //使用包含的头文件off_t lseek(int fd, off_t offset, int whence); //函数原型
函数功能:
将文件读写指针相对whence移动offset个字节(就是键盘打字输入时候的位置,光标的位置)
函数返回值:
lseek函数调用成功,返回一个偏移值(偏移数量),
函数参数:
1.int fd :文件描述符
2.off_t offset:针对whence位置的偏移数量
3.int whence:
whence有三个宏的定义
A. SEEK_SET :将光标移动到文件第一个位置
B. SEEK_CUR:将光标移动到当前位置
C. SEEK_END:将光标移动到文件末尾位置
三、read与lseek的结合使用
代码演示:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <unistd.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int fd;
char *buf = "yyds";
int n_write;
int n_read;
fd = open("./file",O_RDWR);
if(fd == -1){
fd = open("./file",O_RDWR|O_CREAT,0600);
if(fd > 0){
puts("success create");
}else{
puts("creation failure");
}
}
printf("fd = %d\n",fd);
n_write = write(fd,buf,strlen(buf)); //将buf的数据写入到文件里面(描述符fd)。
if(n_write != -1){
printf("write %d byte to file\n",n_write);
}
//注意!!!!write写入到文件里面后,文件读写指针偏移到了末尾
lseek(fd,0,SEEK_SET);//重新把文件读写的指针偏移到文件头的位置,为下一步读取read做准备
char *readbuf;
readbuf = (char *)malloc(sizeof(char)*n_write);
n_read = read(fd,readbuf,n_write);//读取文件的内容,把内容数据读取到缓冲区readbuf
printf("read %d,readbuf %s\n",n_read,readbuf); //打印读取的内容
close(fd); //最后别忘记关闭文件,防止文件出错
return 0;
}
四、根据lseek函数的返回值,可以用lseek函数计算出文件内容的大小
例如:有一个file文件,file文件里面的内容是 yyds666!!!
这个字符串大小是(包含字符串的 '\0'结束标志 )11个字节
用ls file -l 指令查看:file文件的大小
可以看到file文件大小是11
如何用lseek函数计算出文件file的大小?
代码演示:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <unistd.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int fd;
fd = open("./file",O_RDWR); //可读可写的方式打开file文件
int n_lseek = lseek(fd,0,SEEK_END);//将文件的读写指针偏移到文件的尾巴,lseek返回偏移数
printf("n_lseek = %d \n",n_lseek); //打印文件内容偏移数量,
//重点!!!可以利用lseek函数偏移的文件末尾,返回的偏移数量知道文件内容的字符数量大小
close(fd);
return 0;
}
~
~
运行结果:
lseek的计算出open的file文件大小是11字节