1. 程式人生 > >linux下檔案的大小到底多大

linux下檔案的大小到底多大

檔案的大小和實際佔用的空間,是倆回事兒,一般情況下,檔案大小 < 其佔用空間的大小, 即 
ls -al file_name 小於 du -sk file_name 的大小 ,原因是:佔用空間取決於檔案系統的塊(block)的大小,linux一般預設是4k(4096) ,因此,一個大小為1個位元組的檔案,最小也要佔用4k.但是,如果檔案有空洞,那麼就會相反,比如,向一個偏移很大的地址寫入資料(超過檔案尾端),那麼檔案裡面就會形成空洞,這個空洞佔用檔案大小,但是不佔用實際的磁碟大小.如下是測試程式:

    #include <stdio.h>
    #include <fcntl.h>
    #include <sys/stat.h>
    #include <sys/types.h>
    #include <unistd.h>
    #include <string.h>
    
    #define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
    
    const char *pBegin = "hello world ";
    const char *pEnd = "hellok kitty ";
    
    void err_prt(const char *msg){
        printf("%s", msg);
    }
    
    int main(int argc, char *argv[]){
        int fd;
        if((fd = creat("./file.test", FILE_MODE)) < 0)
            err_prt("creat error");
        if(write(fd, pBegin, strlen(pBegin)) != (unsigned int)strlen(pBegin))      
            err_prt("buf1 write error");
        if(lseek(fd, 10240, SEEK_SET) == -1)   
            err_prt("lseek error");
        if(write(fd, pEnd, strlen(pEnd)) != (unsigned int)strlen(pEnd))  
            err_prt("write error");
        return 0;
    }


ls -al file.test
-rw-r–r-- 1 zzc zzc 10253 11月 19 17:49 file.test

du -sh file.test
8.0K file.test

vim file.test 可以看出來,只有檔案起始有寫入的字串,其它地方都是空0,檔案磁碟佔用空間8K,是因為起始寫入的倆個字串,各佔據一個檔案塊,所以是8K。我的公眾號:時光流轉 :,歡迎更多一起學習溝通分享。