利用代码来查看文件的大小
在Linux中有一句真理:一切皆为文件
首先来留意一个有用的函数 lseek。它就可以来查看文件的长度。
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd,off_t offset,int whence);
****
其中:参数offset的解释与参数whence的值有关
1.若whence是SEEK_SET,则将该文件的位移量设置为距文件开始处offset个字节
2.若whence是SEEK_CUR,则将该文件的位移量设置为其当前值offset个字节,offset可为正或负
3.若whence是SEEK_END,则将该文件的位移量设置为文件长度加offset个字节,offset可为正或负。
char * pathname = "know.txt";
int fd = open(pathname,O_RDWR|O_CREAT|O_TRUNC,0644);
if(fd == -1)
{
perror("open error");
exit(-1);
}
char * str = "hello world\n";
int bytes = write(fd,str,strlen(str));
if(bytes < 0)
{
perror("write error");
exit(-1);
}
off_t surrpos = 0;
surrpos = lseek(fd,0,SEEK_SET);
printf("surrpos:%d\n",surrpos);
在程序中,可以把whence设置为SEEK_END,偏移0个字节。得到的surrpos的值对视文件的长度。