因為要儲存持續錄製的影音檔,本機容量的使用量會很快耗盡,於是需要知道本機硬碟容量可用空間剩多少。

接下來直接看程式碼吧~
#include <sys/param.h>
#include <sys/mount.h>
#include <iostream>
int main() {
struct statfs stat;
if (statfs("/", &stat) == 0) {
unsigned long long totalSpace = static_cast<unsigned long long>(stat.f_bsize) * stat.f_blocks;
unsigned long long freeSpace = static_cast<unsigned long long>(stat.f_bsize) * stat.f_bfree;
std::cout << "Total space: " << totalSpace << " bytes\n";
std::cout << "Free space: " << freeSpace << " bytes\n";
} else {
std::cerr << "Error getting disk space information." << std::endl;
}
return 0;
}
輸出結果:
Total space: 494384795648 bytes
Free space: 327567532032 bytes
數字(單位為 bytes)與截圖非常接近,再換算成比較容易懂的 GB 單位即可。
在這個例子中,"/" 是根目錄的路徑,我們可以根據需要更改路徑,來獲取其他檔案系統的資訊。
不同的作業系統,需要引用不同的標頭檔,以上是 MacOS 的範例程式。
參考:ChatGPT。
隨意留個言吧:)~