文件"光标"位置
#include<sys/types.h>
#include<unistd.h>
off_t lseek(int fd, off_t offset, int whence); 作用: 将文件读写指针相对 whence 移动 offset 个字节
显然,参数已经不需要赘述了,offset 就是偏移值,重点:当为负数的时候,就是向前移动,当为正数的时候,就是向 whence 后面移动
在对 Linux 12.04 的测试,结果:当 whence = SEEK_SET, offset<0时,read的字节数为0,读取的字符串(啥也没有) 。当 whence = SEEK_END , offset > 0 时,结果为亦同;
返回值:文件读写指针距文件开头的字节大小,出错,返回-1
给出三个宏定义:
SEEK_SET 指向文件头
SEEK_CUR 指向当前位置
SEEK_END 指向文件尾
老规矩,先上代码:
// 上一节课的憨批代码,打开两次,怎么看都不怎么聪明
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
int openfile(); // 重写好麻烦的说,所以我们封装一个函数吧
int main(){
int fd;
fd = openfile();
char * buf = "12345678 王天潇全场最佳";
int n_write = write(fd, buf, strlen(buf));
if(n_write != -1){ // 代表写入成功嘛
printf("write %d byte to file \n",n_write);
}
// 在读之前,我们必须要先 改变光标的位置
//off_t lseek(int fd, off_t offset, int whence);
int off;
off = lseek(fd,1,SEEK_SET);
if(off != -1){
printf("文件光标 移动成功\n");
}
char * readbuf;
readbuf = (char*)malloc(sizeof(char) * n_write+1);
int n_read = read(fd,readbuf,n_write);
close(fd);
printf("read %d, context:%s\n",n_read,readbuf);
// close(fd);
return 0;
// 划重点 最后这里验证了先关闭文件后输出,自然没问题,read 在之前的描述中明确
// 表述,所读取的 readbuf 会放置于缓冲区中,所以先关闭文件,后输出 readbuf 没有问题
// 但是你要是 在读取之前,即:close(fd); read(); 那你可就凉凉了
}
int openfile(){
int fd;
fd = open("./file1",O_RDWR);
if(fd == -1){
fd = open("./file1",O_RDWR|O_CREAT,0600);
if(fd > 0){
printf("creat file1 success\n");
}
}
printf("open file1 success\n");
return fd;
}
运行结果:
open file1 success
write 30 byte to file
文件光标 移动成功
read 29, context:2345678 王天潇全场最佳
CLC@Embed_Learn:~$
最后再补充一个关于 ls -l 后显示的结果
中间用绿色框框框起的,就是文件包含的字节数,此处file1 写入时,n_write = 30 ,所以文件大小为30。
最后,再补充一个利用 lseek()进行测算文件字节数的方法,记得 lseek() 的返回值是什么来着不?
返回值:文件读写指针距文件开头的字节大小,出错,返回-1
有:
int main(){
int fd;
char * buf = "王天潇真牛逼,全场最佳啊!";
fd = open("./flie1",O_RDWR);
int file_size = lseek(fd,0,SEEK_SET);
close(fd);
printf("%d\n",file_size);
return 0;
}