How to determine how much free space on a drive in Qt? - c++

I'm using Qt and want a platform-independent way of getting the available free disk space.
I know in Linux I can use statfs and in Windows I can use GetDiskFreeSpaceEx(). I know boost has a way, boost::filesystem::space(Path const & p).
But I don't want those. I'm in Qt and would like to do it in a Qt-friendly way.
I looked at QDir, QFile, QFileInfo -- nothing!

I know It's quite old topic but somebody can still find it useful.
Since QT 5.4 the QSystemStorageInfo is discontinued, instead there is a new class QStorageInfo that makes the whole task really simple and it's cross-platform.
QStorageInfo storage = QStorageInfo::root();
qDebug() << storage.rootPath();
if (storage.isReadOnly())
qDebug() << "isReadOnly:" << storage.isReadOnly();
qDebug() << "name:" << storage.name();
qDebug() << "fileSystemType:" << storage.fileSystemType();
qDebug() << "size:" << storage.bytesTotal()/1024/1024 << "MB";
qDebug() << "availableSize:" << storage.bytesAvailable()/1024/1024 << "MB";
Code has been copied from the example in QT 5.5 docs

The new QStorageInfo class, introduced in Qt 5.4, can do this (and more). It's part of the Qt Core module so no additional dependencies required.
#include <QStorageInfo>
#include <QDebug>
void printRootDriveInfo() {
QStorageInfo storage = QStorageInfo::root();
qDebug() << storage.rootPath();
if (storage.isReadOnly())
qDebug() << "isReadOnly:" << storage.isReadOnly();
qDebug() << "name:" << storage.name();
qDebug() << "filesystem type:" << storage.fileSystemType();
qDebug() << "size:" << storage.bytesTotal()/1024/1024 << "MB";
qDebug() << "free space:" << storage.bytesAvailable()/1024/1024 << "MB";
}

I wrote this back when I wrote the question (after voting on QTBUG-3780); I figure I'll save someone (or myself) from doing this from scratch.
This is for Qt 4.8.x.
#ifdef WIN32
/*
* getDiskFreeSpaceInGB
*
* Returns the amount of free drive space for the given drive in GB. The
* value is rounded to the nearest integer value.
*/
int getDiskFreeSpaceInGB( LPCWSTR drive )
{
ULARGE_INTEGER freeBytesToCaller;
freeBytesToCaller.QuadPart = 0L;
if( !GetDiskFreeSpaceEx( drive, &freeBytesToCaller, NULL, NULL ) )
{
qDebug() << "ERROR: Call to GetDiskFreeSpaceEx() failed.";
}
int freeSpace_gb = freeBytesToCaller.QuadPart / B_per_GB;
qDebug() << "Free drive space: " << freeSpace_gb << "GB";
return freeSpace_gb;
}
#endif
Usage:
// Check available hard drive space
#ifdef WIN32
// The L in front of the string does some WINAPI magic to convert
// a string literal into a Windows LPCWSTR beast.
if( getDiskFreeSpaceInGB( L"c:" ) < MinDriveSpace_GB )
{
errString = "ERROR: Less than the recommended amount of free space available!";
isReady = false;
}
#else
# pragma message( "WARNING: Hard drive space will not be checked at application start-up!" )
#endif

There is nothing in Qt at time of writing.
Consider commenting on or voting for QTBUG-3780.

I need to write to a mounted USB-Stick and I got the available size of memory with the following code:
QFile usbMemoryInfo;
QStringList usbMemoryLines;
QStringList usbMemoryColumns;
system("df /dev/sdb1 > /tmp/usb_usage.info");
usbMemoryInfo.setFileName( "/tmp/usb_usage.info" );
usbMemoryInfo.open(QIODevice::ReadOnly);
QTextStream readData(&usbMemoryInfo);
while (!readData.atEnd())
{
usbMemoryLines << readData.readLine();
}
usbMemoryInfo.close();
usbMemoryColumns = usbMemoryLines.at(1).split(QRegExp("\\s+"));
QString available_bytes = usbMemoryColumns.at(3);

I know that this question is already quite old by now, but I searched stackoverflow and found that nobody got solution for this, so I decided to post.
There is QSystemStorageInfo class in QtMobility, it provides cross-platform way to get info about logical drives. For example: logicalDrives() returns list of paths which you can use as parameters for other methods: availableDiskSpace(), totalDiskSpace() to get free and total drive's space, accordingly, in bytes.
Usage example:
QtMobility::QSystemStorageInfo sysStrgInfo;
QStringList drives = sysStrgInfo.logicalDrives();
foreach (QString drive, drives)
{
qDebug() << sysStrgInfo.availableDiskSpace(drive);
qDebug() << sysStrgInfo.totalDiskSpace(drive);
}
This example prints free and total space in bytes for all logical drives in OS. Don't forget to add QtMobility in Qt project file:
CONFIG += mobility
MOBILITY += systeminfo
I used these methods in a project I'm working on now and it worked for me. Hope it'll help someone!

this code`s working for me:
#ifdef _WIN32 //win
#include "windows.h"
#else //linux
#include <sys/stat.h>
#include <sys/statfs.h>
#endif
bool GetFreeTotalSpace(const QString& sDirPath, double& fTotal, double& fFree)
{
double fKB = 1024;
#ifdef _WIN32
QString sCurDir = QDir::current().absolutePath();
QDir::setCurrent(sDirPath);
ULARGE_INTEGER free,total;
bool bRes = ::GetDiskFreeSpaceExA( 0 , &free , &total , NULL );
if ( !bRes )
return false;
QDir::setCurrent( sCurDir );
fFree = static_cast<__int64>(free.QuadPart) / fKB;
fTotal = static_cast<__int64>(total.QuadPart) / fKB;
#else // Linux
struct stat stst;
struct statfs stfs;
if ( ::stat(sDirPath.toLocal8Bit(),&stst) == -1 )
return false;
if ( ::statfs(sDirPath.toLocal8Bit(),&stfs) == -1 )
return false;
fFree = stfs.f_bavail * ( stst.st_blksize / fKB );
fTotal = stfs.f_blocks * ( stst.st_blksize / fKB );
#endif // _WIN32
return true;
}

Related

On Fedora using Qt 5.9.4, I'm unable to simultaneously record and play audio at the same time

I'm trying to write a program in Qt that simultaneously records audio from a microphone and plays it back at the same time. I'm using Qt 5.9.4 and I'm on Fedora 29 (can't update to latest version as our production environment is Fedora 29 -- can't update it, have already asked boss).
I have some barebones code written, as you can see below. But everytime I run the program, I get the following error message:
using null output device, none available
using null input device, none available
I've installed every qt5* package. I have alsa-utils and pulse audio installed as well.
I have also looked at these which more or less helped me but did not solve my problem:
Qt - how to record and play sound simultaneously
https://forum.qt.io/topic/10399/how-to-record-and-play-sound-simultaneously/5
https://www.qtcentre.org/threads/45300-How-to-record-and-play-sound-simultaneously
Qt - No audio output device - Yocto/poky
Qt + conan = using null output device, none available
I don't know if this is a fedora related issue or a Qt related issue. Please help!
myaudiorecorder.h:
#ifndef MYAUDIORECORDER_H
#define MYAUDIORECORDER_H
#include <QAudioFormat>
#include <QAudioDeviceInfo>
#include <QTextStream>
#include <QAudioInput>
#include <QAudioOutput>
#include <QObject>
class MyAudioRecorder : public QObject
{
Q_OBJECT
public:
MyAudioRecorder();
QAudioFormat formatIn;
QAudioFormat formatOut;
QAudioInput *m_audioInput;
QAudioOutput *m_audioOutput;
QAudioDeviceInfo m_InputDevice;
QAudioDeviceInfo m_OutputDevice;
QIODevice *m_input;
QIODevice *m_output;
QAudioDeviceInfo deviceIn;
QAudioDeviceInfo deviceOut;
void getFormat();
void createAudioInput();
void createAudioOutput();
void beginAudio();
};
#endif // MYAUDIORECORDER_H
myaudiorecorder.cpp:
#include "myaudiorecorder.h"
MyAudioRecorder::MyAudioRecorder() {
getFormat();
createAudioInput();
createAudioOutput();
}
void MyAudioRecorder::getFormat(){
formatIn.setSampleSize(8);
formatIn.setCodec("audio/pcm");
formatIn.setByteOrder(QAudioFormat::LittleEndian);
formatIn.setSampleType(QAudioFormat::UnSignedInt);
deviceIn = QAudioDeviceInfo::availableDevices(QAudio::AudioInput).at(1);
if(!deviceIn.isFormatSupported(formatIn)){
QTextStream(stdout) << " default formatIn not supported " << endl;
formatIn = deviceIn.nearestFormat(formatIn);
} else {
QTextStream(stdout) << " default formatIn supported " << endl;
}
deviceOut = QAudioDeviceInfo::availableDevices(QAudio::AudioOutput).at(0);
if(!deviceOut.isFormatSupported(formatOut)) {
QTextStream(stdout) << "1. default formatOut not supported " << endl;
formatOut = deviceOut.nearestFormat(formatOut);
}
}
void MyAudioRecorder::createAudioInput(){
m_audioInput = new QAudioInput(m_InputDevice, formatIn, 0);
}
void MyAudioRecorder::createAudioOutput(){
m_audioOutput = new QAudioOutput(m_OutputDevice, formatOut, 0);
}
void MyAudioRecorder::beginAudio(){
m_output = m_audioOutput->start();
m_input = m_audioInput->start();
}
void MyAudioRecorder::beginAudio(){
m_output = m_audioOutput->start();
m_audioInput->start(m_output);
//Above should do the trick but do check the volume, state and error if any:
qDebug() << "m_audioInput: volume=" << m_audioInput->volume()
<< ", state=" << m_audioInput->state()
<< ", error=" << m_audioInput->error();
qDebug() << "m_audioOutput: volume=" << m_audioOutput->volume()
<< ", state=" << m_audioOutput->state()
<< ", error=" << m_audioOutput->error();
}
you need copy qt Qt/5.9.x/mingw73_64/plugins/audio to you binary directory,not copy qtaudio_windows.dll ,is copy audio folder

Native C++ node.js module addon WinHttp Detect Auto Proxy Config Url Error return

I am stuck in a tight spot and I need some help with some C++ code. This is my first attempt at doing C++ and it born mostly from necessity at this point.
I am trying (unsuccessfully it feels) to build a native NAN module for Node.JS that will be used by an Electron app on Windows.
I need it to return the WinHttpDetectAutoProxyConfigUrl when the users Proxy configuration is set to Auto Detect.
I have built this exact thing in C# for another application and it works seamlessly in our distributed user BYOD environment. However in this case I do not wish to be dependent on the dot.net framework unnecessarily.
Right know I am at the extent of my knowledge when it comes to C++ as most of my knowledge over the years has thus far been theoretical. I am hoping that someone that actually works in C++ daily can look at my code and help correct the error that is happening.
I have been trying to debug using the “std::cout” in VSCode.
As you can see from the output at the bottom of the image, that some of it appears to be working and the code is dropping into the “Get Auto URL” IF block as expected. However the output is very iritic (“�����”) and nothing like the wpad.dat URL I was expecting to see returned from the wpad protocol implemented by the winhttp.dll.
My Problem:
It is as though the result is blank and then the “char buffer[2083];” is being sent to the stdOut and the characters are all encoded wrong.
Any help on this would be very helpful so thanks in advance.
Please see the code below.
main.cpp
#include <nan.h>
#include <Windows.h>
#include <Winhttp.h>
#include <iostream>
#pragma comment(lib, "winhttp.lib")
using namespace std;
// NAN_METHOD is a Nan macro enabling convenient way of creating native node functions.
// It takes a method's name as a param. By C++ convention, I used the Capital cased name.
NAN_METHOD(AutoProxyConfigUrl) {
cout << "AutoProxyConfigUrl" << "\n";
v8::Isolate* isolate = info.GetIsolate(); // args.GetIsolate();
LPWSTR strConfigUrl = NULL;
WINHTTP_CURRENT_USER_IE_PROXY_CONFIG MyProxyConfig;
if(!WinHttpGetIEProxyConfigForCurrentUser(&MyProxyConfig))
{
//check the error DWORD Err = GetLastError();
DWORD Err = GetLastError();
cout << "WinHttpGetIEProxyConfigForCurrentUser failed with the following error number: " << Err << "\n";
switch (Err)
{
case ERROR_FILE_NOT_FOUND:
cout << "The error is ERROR_FILE_NOT_FOUND" << "\n";
break;
case ERROR_WINHTTP_INTERNAL_ERROR:
cout << "ERROR_WINHTTP_INTERNAL_ERROR" << "\n";
break;
case ERROR_NOT_ENOUGH_MEMORY:
cout << "ERROR_NOT_ENOUGH_MEMORY" << "\n";
break;
default:
cout << "Look up error in header file." << "\n";
break;
}//end switch
//TODO this might not be a good idea but it is worth trying
strConfigUrl = L"http://wpad/wpad.dat"; //Default to Fallback wpad
}//end if
else
{
//no error so check the proxy settings and free any strings
cout << "Auto Detect is: " << MyProxyConfig.fAutoDetect << "\n";
if(MyProxyConfig.fAutoDetect){
cout << "Get Auto URL" << "\n";
if (!WinHttpDetectAutoProxyConfigUrl(WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A, &strConfigUrl))
{
cout << "Error getting URL" << "\n";
//This error message is not necessarily a problem and can be ignored if you are using direct connection. you get this error if you are having direct connection.
//check the error DWORD Err = GetLastError();
DWORD Err = GetLastError();
if (ERROR_WINHTTP_AUTODETECTION_FAILED == Err)
{
strConfigUrl = L"http://wpad/wpad.dat"; //Default to Fallback wpad
}
//TODO work out what to do with the other errors
}
}
if(NULL != MyProxyConfig.lpszAutoConfigUrl)
{
wcout << "AutoConfigURL (MyProxyConfig.lpszAutoConfigUrl) is: " << MyProxyConfig.lpszAutoConfigUrl << "\n";
GlobalFree(MyProxyConfig.lpszAutoConfigUrl);
}
if(NULL != MyProxyConfig.lpszProxy)
{
wcout << "AutoConfigURL (MyProxyConfig.lpszProxy) is: " << MyProxyConfig.lpszProxy << "\n";
GlobalFree(MyProxyConfig.lpszProxy);
}
if(NULL != MyProxyConfig.lpszProxyBypass)
{
wcout << "AutoConfigURL is: " << MyProxyConfig.lpszProxyBypass << "\n";
GlobalFree(MyProxyConfig.lpszProxyBypass);
}
}//end else
//cout << "strConfigUrl" << strConfigUrl << "\n";
char buffer[2083];
wcstombs( buffer, strConfigUrl, wcslen(strConfigUrl) ); // Need wcslen to compute the length of the string
// convert it to string
std::string returnUrl(buffer);
// Create an instance of V8's String type
auto message = Nan::New(returnUrl).ToLocalChecked();
// 'info' is a macro's "implicit" parameter - it's a bridge object between C++ and JavaScript runtimes
// You would use info to both extract the parameters passed to a function as well as set the return value.
info.GetReturnValue().Set(message);
if(strConfigUrl)
GlobalFree(strConfigUrl);
}
// Module initialization logic
NAN_MODULE_INIT(Initialize) {
// Export the `Hello` function (equivalent to `export function Hello (...)` in JS)
NAN_EXPORT(target, AutoProxyConfigUrl);
}
// Create the module called "addon" and initialize it with `Initialize` function (created with NAN_MODULE_INIT macro)
NODE_MODULE(proxyautodetect, Initialize);
main.js
// note that the compiled addon is placed under following path
//const {AutoProxyConfigUrl} = require('./build/Release/proxyautodetect.node');
const {AutoProxyConfigUrl} = require('./build/Debug/proxyautodetect.node');
// `Hello` function returns a string, so we have to console.log it!
console.log(AutoProxyConfigUrl());
Build and Run output:
C:\Code\Work\wpad-auto-detect>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild --debug ) else (node "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild --debug )
Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch.
main.cpp
win_delay_load_hook.cc
Creating library C:\Code\Work\wpad-auto-detect\build\Debug\proxyautodetect.lib and object C:\Code\Work\wpad-auto-detect\build\Debug\proxyautodet
ect.exp
proxyautodetect.vcxproj -> C:\Code\Work\wpad-auto-detect\build\Debug\\proxyautodetect.node
PS C:\Code\Work\wpad-auto-detect> npm start
> proxyautodetect#1.0.0 start C:\Code\Work\wpad-auto-detect
> node main.js
AutoProxyConfigUrl
Auto Detect is: 1
Get Auto URL
"
"��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������1��J╗
PS C:\Code\Work\wpad-auto-detect>
Image of code output
I did a sort of Trim
int urlLen = wcslen(strConfigUrl) ;
#if DEBUG
cout << "strConfigUrl wcslen : " << urlLen << "\n";
#endif
char buffer[2083]; //This is the max length a URL can be in IE
wcstombs( buffer, strConfigUrl, wcslen(strConfigUrl) ); // Need wcslen to compute the length of the string
// convert it to string
std::string returnUrl(buffer);
// Create an instance of V8's String type and Return only the Length needed so kind of Trim the extra char
auto message = Nan::New(returnUrl.substr(0, urlLen)).ToLocalChecked();

QSerialPort::readLine doesn't work as expected on MS Windows

I'm trying to connect a micro-controller with my desktop PC via USB-serial cable.
The OS of my desktop PC is Windows 8.1, and USB-serial cable is TTL-232R-3V3. (FTDI)
(Qt version: 5.2.0 beta1, QtCreator Version: 3.0, Compiler: MSVC2012)
Now I'm trying read/write loop-back tests, and that's why RX/TX pin of USB-serial cable are connected with each other.
Here is my code.
#include <QtCore/QCoreApplication>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QtCore/QDebug>
#define PORT_NAME "COM3"
#define BAUDRATE 19600
#define TIMEOUT_MS 1000
QT_USE_NAMESPACE
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSerialPort pSerial(PORT_NAME);
const char strMsg[] = "#1:Send data line \n #2:Send data line\n #3:Send data line end\n";
char strBuf[256];
qint64 nByte;
if(pSerial.open(QIODevice::ReadWrite)){
pSerial.setBaudRate(BAUDRATE);
qDebug() << "OPEN PASS";
pSerial.write(strMsg);
pSerial.flush();
if(pSerial.waitForBytesWritten(TIMEOUT_MS)){
qDebug() << "WRITE PASS";
}
pSerial.waitForReadyRead(TIMEOUT_MS);
while(true){
if( pSerial.canReadLine()){
qDebug() << "CAN READ LINE";
nByte = pSerial.readLine(strBuf,sizeof(strBuf));
qDebug() << "Length: " << nByte;
qDebug() << "Read data: " << strBuf;
}
}
pSerial.close();
} else {
qDebug() << "OPEN FAIL\n";
}
return a.exec();
}
When the program starts to run, the result is different than I expected.
Only first line of sent data can be received. So, "Read data: #1 Send data line" is printed
on console. But the rest of sent data will never be received. Does anyone know why?
Any help would be appreciated.
Thanks in advance.
EDIT: I revised my code according to Papp's comment.Then it works as I expected.
All sent message has been received.
Does it mean I misunderstand the usage about readLine() or canReadLine()?
// while(true){
// if( pSerial.canReadLine()){
// qDebug() << "CAN READ LINE";
// nByte = pSerial.readLine(strBuf,sizeof(strBuf));
// qDebug() << "Length: " << nByte;
// qDebug() << "Read data: " << strBuf;
// }
// }
pSerial.waitForReadyRead(TIMEOUT_MS);
QByteArray readData = pSerial.readAll();
while (pSerial.waitForReadyRead(TIMEOUT_MS)) {
readData.append(pSerial.readAll());
}
qDebug() << "Read data: " << readData;
EDIT 2nd time : Following code also works for me.
while(true){
if( pSerial.waitForReadyRead(TIMEOUT_MS) && pSerial.canReadLine()){ // I revised this line
qDebug() << "CAN READ LINE";
nByte = pSerial.readLine(strBuf,sizeof(strBuf));
qDebug() << "Length: " << nByte;
qDebug() << "Read data: " << strBuf;
qDebug() << "Error Message: " << pSerial.errorString();
}
}
That is because you need to read in a loop like this:
QByteArray readData = serialPort.readAll();
while (serialPort.waitForReadyRead(5000))
readData.append(serialPort.readAll());
Please see the creadersync example for the details what I added to 5.2. You can also check the creaderasync example for non-blocking operation.
To be fair, we have not tested readLine that much, but it works for me on Unix, so does it on Windows for someone else.
The mistake that you've made is expecting to receive all the sent data when waitForReadyRead returns. When waitForReadyRead finishes, all you're guaranteed is some data being available to be read. It may be as little as one character, not necessarily a whole line.
The loop from your last modification is the almost correct way to do it. You should nest reading of the lines in a separate loop. The following code is how it should be done, and agrees with the semantics of QIODevice:
while (pSerial.waitForReadyRead(TIMEOUT_MS)) {
while (pSerial.canReadLine()) {
qDebug() << "NEW LINE";
QByteArray line = pSerial.readLine();
qDebug() << "Length: " << line.size();
qDebug() << "Read data: " << line;
qDebug() << "Error Message: " << pSerial.errorString();
}
}
qDebug << "TIMED OUT";
Note that none of this code should even run in the GUI thread. Ideally you should move it to a QObject, use the signals emitted by QIODevice (and thus QSerialPort), and move that object to a separate thread.
The GUI thread can sometimes block for long periods of time, it's not normally desirable to have it disturb the timeliness of your device communication. Similarly, you don't want device timeouts to block the GUI thread. Both are equally bad and are a very common source of bad user experience. Qt makes multithreading very easy - leverage it for your user's sake, and do it properly.
On Linux I have to do it this way to receive ASCII text ending with '\n'
QByteArray readData = pSerial.readAll();
while (readData[readData.length() - 1] != '\n') {
pSerial.waitForReadyRead(5000);
readData.append(pSerial.readAll());
}
QString result(readData);
QSerialPort::readLine() doesn't work for me either

Howto get hardware information in Linux using C++

I need to get specifications of hard disk on both Win and *nix machines. I used <hdreg.h> on Linux like this:
static struct hd_driveid hd;
int device;
if ((device = open("/dev/sda", O_RDONLY | O_NONBLOCK)) < 0)
{
cerr << "ERROR: Cannot open device /dev/sda \n";
exit(1);
}
if (!ioctl(device, HDIO_GET_IDENTITY, &hd))
{
cout << hd.model << endl;
cout << hd.serial_no << endl;
cout << hd.heads << endl;
}
I need hd_driveid to tell me some more information about disk. I want to know:
Number of partitions
Specifications of each partition (format, label, flags, size, start point, number of tracks etc.)
Number of tracks per cylinder
Number of total tracks
Maximum block size
Minimum Block size
Default block size
Total size of device
My questions are:
Is there a common
(platform-independent) way to
connect hardware? I would like use
same code for win and *nix. (even if
there was no way other than
embedding assembly code into cpp)
If there isn't, how do I get above information in *nix?
Nearly everything in your list has nothing to do with "specifications of hard disk":
The number of partitions depends on reading the partition table, and if you have any extended partitions, the partition tables of those partitions. The OS will usually do this bit for you when the device driver loads.
Partition information (namely the volume label) typically isn't available in the partition table. You need to guess the file system type and parse the file system header. The only thing in the partition table is the "type" byte, which doesn't tell you all that much, and the start/size.
Hard drives won't give you "real" CHS information. Additionally, the CHS information that the drive provides is "wrong" from the point of view of the BIOS (the BIOS does its own fudging).
Hard drives have a fixed sector size, which you can get with hd_driveid.sector_bytes (usually 512, but some modern drives use 4096). I'm not aware of a maximum "block size", which is a property of the filesystem. I'm also not sure why this is useful.
The total size in sectors is in hd_driveid.lba_capacity_2. Additionally, the size in bytes can probably be obtained with something like
#define _FILE_OFFSET_BITS 64
#include <sys/types.h>
#include <unistd.h>
...
off_t size_in_bytes = lseek(device, 0, SEEK_END);
if (size_in_bytes == (off_t)-1) { ... error, error code in ERRNO ... }
Note that in both cases, it'll probably be a few megabytes bigger than sizes calculated by C×H×S.
It might help if you told us why you wanted this information...
//-------------------------------------------------
// Without Boost LIB usage
//-------------------------------------------------
#include <sys/statvfs.h>
#include <sys/sysinfo.h>
//-------------------------------------------------
stringstream strStream;
unsigned long hdd_size;
unsigned long hdd_free;
ostringstream strConvert;
//---
struct sysinfo info;
sysinfo( &info );
//---
struct statvfs fsinfo;
statvfs("/", &fsinfo);
//---
//---
unsigned num_cpu = std::thread::hardware_concurrency();
//---
ifstream cpu_freq("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_cur_freq");
strStream << cpu_freq.rdbuf();
std::string cpufrequency = strStream.str();
//---
strStream.str("");
ifstream cpu_temp("/sys/class/thermal/thermal_zone0/temp");
strStream << cpu_temp.rdbuf();
strConvert<< fixed << setprecision(2) << std::stof(strStream.str());
std::string cputemp = strConvert.str();
//---
std::string mem_size = to_string( (size_t)info.totalram * (size_t)info.mem_unit );
//---
hdd_size = fsinfo.f_frsize * fsinfo.f_blocks;
hdd_free = fsinfo.f_bsize * fsinfo.f_bfree;
//---
std::cout << "CPU core number ==" << num_cpu << endl;
std::cout << "CPU core speed ==" << cpufrequency << endl;
std::cout << "CPU temperature (C) ==" << cputemp << endl;
//---
std::cout << "Memory size ==" << mem_size << endl;
//---
std::cout << "Disk, filesystem size ==" << hdd_size << endl;
std::cout << "Disk free space ==" << hdd_free << endl;
//---
No, there is no platform-independent way. There is even no *nix way. There is just Linux way.
In Linux, all relevant information is available in various files in the /proc filesystem. The /proc/devices will tell you what devices there are (the files in /dev/ may exist even when the devices are not available, though opening them will fail in that case), /proc/partitions will tell you what partitions are available on each disk and than you'll have to look in the various subdirectories for the information. Just look around on some linux system where is what you need.
For GNU/Linux have a look at this: obtaining hard disk metadata
//Piece of code working for me with Boost LIB usage
//-----------------------------------------------------
#include <sys/sysinfo.h>
#include <boost/filesystem.hpp>
//---
using namespace boost::filesystem;
//---
struct sysinfo info;
sysinfo( &info );
//---
space_info si = space(".");
//---
unsigned num_cpu = std::thread::hardware_concurrency();
//---
ifstream cpu_freq("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_cur_freq");
ifstream cpu_temp("/sys/class/thermal/thermal_zone0/temp");
//---
std::string cpunumber = to_string(num_cpu);
std::string cpufrequency = cpu_freq.str();
std::string cputemp = cpu_temp.str();
std::string mem_size = to_string( (size_t)info.totalram * (size_t)info.mem_unit );
std::string disk_available = to_string(si.available);
std::string fslevel = to_string( (si.available/si.capacity)*100 );
//---

How to get CPU usage in Qt?

I have a main server and 4 computers connected. How can I learn which computer use how much CPU and disk.
I write code using Qt and C++.
Qt does not have an API for this. You'll need to use the platforms native API.
Maybe this can help you:
#include <QDebug>
#include <QProcess>
int main(void){
setenv("LC_NUMERIC", "C",1);
QProcess process;
process.start("/usr/bin/uptime",{},QIODevice::ReadWrite);
process.waitForFinished();
//Get results
QString output = process.readAllStandardOutput();
QString err = process.readAllStandardError();
//Get load portion
QString loads=output.section("load average: ",1,1);
QString load_lastmin=loads.section(" ",0,0);
load_lastmin.remove(load_lastmin.size()-1,1);
//For debug
qDebug() << "Output:" << output;
qDebug() << "Error:" << err;
qDebug() << "Loads:" << loads;
qDebug() << "Load last min:" << load_lastmin;
return 0;
}
Result example:
Output: " 10:04:33 up 3 days, 21:39, 1 user, load average: 0.55, 0.71, 0.78\n"
Error: ""
Loads: "0.55, 0.71, 0.78\n"
Load last min: "0.55"