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。我的公眾號:時光流轉 ,歡迎更多一起學習溝通分享。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM