1. 程式人生 > >linux 使用lseek函式來獲取檔案大小

linux 使用lseek函式來獲取檔案大小

一、獲取檔案大小

/*測得檔案大小*/  
int filelen;
int fd;

int filelen= lseek(fd,0L,SEEK_END);  
lseek(fd,0L,SEEK_SET);  
printf("file size is %d\n",filelen);  

二、lseek使用說明

表頭檔案
#include<sys/types.h>
#include<unistd.h>


定義函式
off_t lseek(int filde,off_t offset ,int whence);

EEK_SET 將讀寫位置指向檔案頭後再增加offset個位移量。
SEEK_CUR 以目前的讀寫位置往後增加offset個位移量。 SEEK_END 將讀寫位置指向檔案尾後再增加offset個位移量。 當whence 值為SEEK_CUR 或SEEK_END時,引數offet允許負值的出現。 下列是較特別的使用方式: 1) 欲將讀寫位置移到檔案開頭時: lseek(int fildes,0,SEEK_SET); 2) 欲將讀寫位置移到檔案尾時: lseek(int fildes,0,SEEK_END); 3) 想要取得目前檔案位置時: lseek(int fildes,0,SEEK_CUR);

返回值
當呼叫成功時則返回目前的讀寫位置,也就是距離檔案開頭多少個位元組。若有錯誤則返回-1,errno 會存放錯誤程式碼。
可能設定erron的錯誤程式碼:
EBADF: fildes不是一個開啟的檔案描述符。
ESPIPE:檔案描述符被分配到一個管道、套接字或FIFO。
EINVAL:whence取值不當。


程式碼列子:

#define BUFFER_SIZE 1024
int main(int argc,char **argv)  
{  
    int  readfd, writefd;  
    long filelen=0;  
    int  ret=1;  
    char buffer[BUFFER_SIZE];  
    char *ptr;  
  
    /*開啟原始檔*/   
    if((readfd=open("test.txt", O_RDONLY|O_CREAT)) == -1)   
    {   
		printf("Open Error\n");   
        exit(1);   
    }   
   
      /*建立目的檔案*/   
    if((writefd=open("dest.txt", O_WRONLY|O_CREAT)) == -1)   
    {   
        printf("Open Error\n");   
        exit(1);   
    }   
    
    /*測得檔案大小*/  
    filelen= lseek(readfd,0L,SEEK_END);  
    lseek(readfd,0L,SEEK_SET);  
    printf("read file size is %d\n",filelen);  
    
    /*進行檔案拷貝*/  
    while(ret)   
    {   
        ret= read(readfd, buffer, BUFFER_SIZE);  
        if(ret==-1)  
        {  
            printf("read Error\n");   
            exit(1);          
        }  
        write(writefd, buffer, ret);  
        filelen-=ret;  
        bzero(buffer,BUFFER_SIZE);  
    }   

    close(readfd);   
    close(writefd);   
	exit(0);   
}