c++ 获取当前的磁盘剩余空间

695 阅读1分钟
    long getLeftSpace(string path) {
    //string str_disk_name = path.substr(0, 3);
    string str_disk_name = path;
    DWORD64 qwFreeBytesToCaller = 0;
    DWORD64 qwTotalBytes = 0;
    DWORD64 qwFreeBytes = 0;
    DWORD64 qwFreeBytesToCallerMunit = 0;
    ///使用GetDiskFreeSpaceEx获取磁盘信息并打印结果
    BOOL bResult = GetDiskFreeSpaceExA(str_disk_name.c_str(),
        (PULARGE_INTEGER)&qwFreeBytesToCaller,
        (PULARGE_INTEGER)&qwTotalBytes,
        (PULARGE_INTEGER)&qwFreeBytes);
    /// 读取成功
    if (bResult)
    {
        printf("使用GetDiskFreeSpaceEx获取磁盘空间信息\n");
    
    /// 如果还剩下5G空闲空间,则禁止写入日志
    qwFreeBytesToCallerMunit = qwFreeBytesToCaller / (1024 * 1024);
    cout << "获得剩余的空闲空间(字节):" + to_string(qwFreeBytesToCallerMunit) + "MB" << endl;
​
    qwFreeBytesToCaller /= (1024 * 1024 * 1024);
    if (5 >= qwFreeBytesToCaller) {
        cout << "the left space is not enough." << endl;
    }
​
    printf("可获得的空闲空间(字节): \t%I64d\n", qwFreeBytesToCaller);
    printf("空闲空间(字节): \t\t%I64d\n", qwFreeBytes);
    printf("磁盘总容量(字节): \t\t%I64d\n", qwTotalBytes);
}
else {
    cout << "read fail" << endl;
}
​
}