linux c获取磁盘大小

针对未挂载,只有设备名称的设备,用ioctl获取大小,statfs只能正确获取mount设备的大小

#include 
#include  
#include 
#include  

//dev/nvme0n1
int checkDisk(const char *path, PQ_U64 *size)
{
    int ret = 0, fd = 0;
    PQ_U64 blockSize, logicSize, totalSize;

    if(0 != access(path, F_OK | R_OK | W_OK))
    {
        PQ_PRINT(PQ_WARNING, "access %s failed\n", path);
        ret = PQ_FAILURE;   
        goto end;
    }
    
    if ((fd = open(path, O_RDONLY)) < 0)  
    {  
        PQ_PRINT(PQ_ERROR,"open %s error\n", path);  
        ret = PQ_FAILURE;   
        goto end;  
    }  
    //总大小
    if ((ret = ioctl(fd, BLKGETSIZE64, &totalSize)) < 0)  
    {  
        PQ_PRINT(PQ_ERROR,"ioctl BLKGETSIZE64 error\n");  
        ret = PQ_FAILURE;   
        goto end;
    } 
    // //物理块大小,ssd一般为4K
    // if ((ret = ioctl(fd, BLKBSZGET, &blockSize)) < 0)  
    // {  
    //     PQ_PRINT(PQ_ERROR,"ioctl BLKBSZGET error \n");  
    //     ret = PQ_FAILURE;   
    //     goto end;
    // } 
    // //逻辑块大小,通常512bytes
    // if ((ret = ioctl(fd, BLKPBSZGET, &totalBlocks)) < 0)  
    // {  
    //     PQ_PRINT(PQ_ERROR,"ioctl BLKBSZGET error \n");  
    //     ret = PQ_FAILURE;   
    //     goto end;
    // }
    // PQ_PRINT(PQ_DEBUG, "blockSize=%lld, logicSize=%lld, totalSize=%lld\n", blockSize, logicSize, totalSize);

    PQ_PRINT(PQ_DEBUG, "totalSize=%lld G\n", (totalSize>>30));

end:
    if(fd)
        close(fd);
    return ret;
}

你可能感兴趣的:(linux)