利用程序查看文件的大小 lseek函數

利用代碼來查看文件的大小

在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的值對視文件的長度。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章