Linux 在執行 /bin/ls -l 時如何計算總區塊數?

Linux 在執行 /bin/ls -l 時如何計算總區塊數?

我試圖弄清楚程式如何/bin/ls -l計算目錄的總大小(區塊計數)。我的意思是它在目錄內容之前打印的輸出。total number

這裡有一個類似的問題:https://stackoverflow.com/questions/7401704/what-is-that-total-in-the-very-first-line-after-ls-l但它沒有完全回答問題,也沒有準確地解釋它是如何計算的。

我嘗試添加分配的 512B 區塊數 對於目錄中的所有(非隱藏)檔案。這是我嘗試的方法(用 C 語言):

 int getBlockSize(char* directory) {
   int size = 0;

   DIR *d;
   struct dirent *dir;
   struct stat fileStat;
   d = opendir(directory);
   if (d) {
       while ((dir = readdir(d)) != NULL) {
           if (dir->d_name[0] != '.') { // Ignore hidden files
               // Create the path to stat
               char info_path[PATH_MAX + 1];
               strcpy(info_path, directory);
               if (directory[strlen(directory) - 1] != '/')
                   strcat(info_path, "/");
               strcat(info_path, dir->d_name);

               stat(info_path, &fileStat);

               size += fileStat.st_blocks;
           }
       }
   }

   return size;
}

然而,與命令相比,這給了我一個非常不同的數字ls

我的方法有什麼「問題」?ls總數如何計算?

編輯:

為了測試,我創建了一個包含文件的資料夾test_file1.txttest_file2.txt每個文件都包含文字Hello World!。當我運行時,ls -l我得到以下輸出

total 1
-rw-------. 1 aaa111 ugrad 13 Oct 27 13:17 test_file1.txt
-rw-------. 1 aaa111 ugrad 13 Oct 27 13:17 test_file2.txt

但是,當我使用上面的方法運行程式碼時,我得到了

total 2
-rw-------. 1 aaa111 ugrad 13 Oct 27 13:17 test_file1.txt
-rw-------. 1 aaa111 ugrad 13 Oct 27 13:17 test_file2.txt 

答案1

在 Ubuntu 上,預設ls值為GNUls, 哪個預設為 1024 位元組塊大小其“總”線。這解釋了您的方法與您的方法之間的輸出差異ls:您的方法顯示的區塊數是雙倍的,因為它計算的是 512 位元組區塊。

有多種方法可以強制 GNUls以 512 位元組區塊計數(請參閱上面的連結);最可靠的是設定LS_BLOCK_SIZE

LS_BLOCK_SIZE=512 ls -l

ls您在 Linux 上可能遇到的另一個實作是忙碌盒 ls;它也對「total」行使用 1024 位元組的區塊大小,並且不能配置為使用任何其他大小。

相關內容