Archives

Date

Windows SDK : How can I check the free space on a partition?

Q: How can I check the free space on a partition?

A:

BOOL GetFreeSpaceString(LPCTSTR drivespec, ULONG mode, LPTSTR s)
{
DWORD sectorsPerCluster,
bytesPerSector,
numberOfFreeClusters,
totalNumberOfClusters, total;

if
(!GetDiskFreeSpace(drivespec,
&sectorsPerCluster,
&bytesPerSector,
&numberOfFreeClusters,
&totalNumberOfClusters))
return FALSE;

total = numberOfFreeClusters*bytesPerSector*sectorsPerCluster;
if
(mode==BYTES)
_stprintf(s, _T(
"%lu bytes available"), total);
else if
(mode==KBYTES)
_stprintf(s, _T(
"%1.1fK available"), (float)(total/(float)mode));
else
_stprintf(s, _T("%1.1f MB available"), (float)(total/(float)mode));
return TRUE;
}


Note: Most of the material in this article is taken from codeguru.com


Recommended Reading :

Windows SDK : How to get the available logical partitions on my PC?

Q: How to get the available logical partitions on my PC?

A:

#include <iostream>

// Get logical drives
DWORD dwLogicalDrives = ::GetLogicalDrives();
if
(dwLogicalDrives)
{
for(int iCnt = 0; iCnt < 32; ++iCnt)
{
memset(szDriveRoot,
0, sizeof(szDriveRoot));

if
(dwLogicalDrives & (1 << iCnt))
{
// Set drive root
sprintf(szDriveRoot, "%c:\\", iCnt + 'A');
// Determine partition type
UINT uiDriveType = ::GetDriveType(szDriveRoot);
switch
(uiDriveType)
{
// Unknown
case DRIVE_UNKNOWN:
std::cout <<
"Partition " << szDriveRoot << " -> " << "Unknown" << std::endl;
break;
// Root path invalid
case DRIVE_NO_ROOT_DIR:
std::cout <<
"Partition " << szDriveRoot << " -> " << "Root path invalid"
<< std::endl;
break;
// Removable drive
case DRIVE_REMOVABLE:
std::cout <<
"Partition " << szDriveRoot << " -> " << "Removable drive"
<< std::endl;
break;
// Fixed drive
case DRIVE_FIXED:
std::cout <<
"Partition " << szDriveRoot << " -> " << "Fixed drive"
<< std::endl;
break;
// Network drive
case DRIVE_REMOTE:
std::cout <<
"Partition " << szDriveRoot << " -> " << "Network drive"
<< std::endl;
break;
// CD-ROM
case DRIVE_CDROM:
std::cout <<
"Partition " << szDriveRoot << " -> " << "CD-ROM"
<< std::endl;
break;
// RAM-Disk
case DRIVE_RAMDISK:
std::cout <<
"Partition " << szDriveRoot << " -> " << "RAM-Disk"
<< std::endl;
break;
}
}
}
}
Note: Most of the material in this article is taken from codeguru.com
Recommended Reading :

Windows SDK : How to get information about a partition?

Q: How to get information about a partition?

A:

#include <iostream>
#include <iomanip>

TCHAR szVolumeName[
100] = "";
TCHAR szFileSystemName[10] = "";
DWORD dwSerialNumber = 0;
DWORD dwMaxFileNameLength = 0;
DWORD dwFileSystemFlags = 0;
if
(::GetVolumeInformation("c:\\",
szVolumeName,
sizeof(szVolumeName),
&dwSerialNumber,
&dwMaxFileNameLength,
&dwFileSystemFlags,
szFileSystemName,
sizeof(szFileSystemName)) == TRUE)
{
std::cout <<
"Volume name = " << szVolumeName << std::endl
<<
"Serial number = " << dwSerialNumber << std::endl
<<
"Max. filename length = " << dwMaxFileNameLength << std::endl
<<
"File system flags = $" << std::hex << dwFileSystemFlags << std::endl
<<
"File system name = " << szFileSystemName << std::endl;
}

 

Note: Most of the material in this article is taken from codeguru.com
Recommended Reading :

Windows SDK : How to check for the existance of a directory/file?

Q: How to check for the existance of a directory/file?

A:

CString szPath("c:\\windows");
CString szFile("c:\\test.txt");

DWORD dwAttr = GetFileAttributes(szPath);
if
(dwAttr == 0xffffffff)
{
DWORD dwError
= GetLastError();
if
(dwError == ERROR_FILE_NOT_FOUND)
{
// file not found
}
else if(dwError == ERROR_PATH_NOT_FOUND)
{
// path not found
}
else if(dwError == ERROR_ACCESS_DENIED)
{
// file or directory exists, but access is denied
}
else
{
// some other error has occured
}
}
else
{
if(dwAttr & FILE_ATTRIBUTE_DIRECTORY)
{
// this is a directory
if(dwAttr & FILE_ATTRIBUTE_ARCHIVE)
// Directory is archive file
if(dwAttr & FILE_ATTRIBUTE_COMPRESSED)
// Directory is compressed
if(dwAttr & FILE_ATTRIBUTE_ENCRYPTED)
// Directory is encrypted
if(dwAttr & FILE_ATTRIBUTE_HIDDEN)
// Directory is hidden
if(dwAttr & FILE_ATTRIBUTE_READONLY)
// Directory is read-only
if(dwAttr & FILE_ATTRIBUTE_REPARSE_POINT)
// Directory has an associated reparse point
if(dwAttr & FILE_ATTRIBUTE_SYSTEM)
// Directory is part or used exclusively by the operating system
}
else
{
// this is an ordinary file
if(dwAttr & FILE_ATTRIBUTE_ARCHIVE)
// File is archive file
if(dwAttr & FILE_ATTRIBUTE_COMPRESSED)
// File is compressed
if(dwAttr & FILE_ATTRIBUTE_ENCRYPTED)
// File is encrypted
if(dwAttr & FILE_ATTRIBUTE_HIDDEN)
// File is hidden
if(dwAttr & FILE_ATTRIBUTE_NOT_CONTENT_INDEXED)
// File will not be indexed
if(dwAttr & FILE_ATTRIBUTE_OFFLINE)
// Data of file is not immediately available
if(dwAttr & FILE_ATTRIBUTE_READONLY)
// File is read-only
if(dwAttr & FILE_ATTRIBUTE_REPARSE_POINT)
// File has an associated reparse point
if(dwAttr & FILE_ATTRIBUTE_SPARSE_FILE)
// File is a sparse file
if(dwAttr & FILE_ATTRIBUTE_SYSTEM)
// File is part or used exclusively by the operating system
if(dwAttr & FILE_ATTRIBUTE_TEMPORARY)
// File is being used for temporary storage
}
}

 

Note: Most of the material in this article is taken from codeguru.com


Recommended Reading :

Windows SDK : How to retrieve the version information of my application?

Q: How to retrieve the version information of my application?
A: To retrieve the version information you can use the following functions...

DWORD GetFileVersionInfoSize(LPTSTR lptstrFilename, LPDWORD lpdwHandle)

BOOL GetFileVersionInfo(LPTSTR lptstrFilename,
DWORD dwHandle,
DWORD dwLen,
LPVOID lpData)

BOOL VerQueryValue(const LPVOID pBlock,
LPTSTR lpSubBlock,
LPVOID *lplpBuffer,
PUINT puLen)

DWORD VerLanguageName(DWORD wLang, LPTSTR szLang, DWORD nSize)

'GetFileVersionInfoSize()' returns the size of the version information. 'GetFileVersionInfo()' uses information retrieved by 'GetFileVersionInfoSize()' to retrieve a structure that contains the version information. 'VerQueryValue()' retrieves a specific member from that structure. Your setup program needs to call those function depending on the error code returned by e.g. 'VerInstallFile()'.

The following is an example class which wraps the whole thing...

// version.hpp

#ifndef VERSION
#define VERSION
#pragma warning(disable : 4505 4710)
#pragma comment(lib, "version.lib")

#include <string>
#include <sstream>
#include <iomanip>
#include <exception>
#include <new>
#include <windows.h>

namespace version_nmsp
{
struct language
{
WORD language_
;
WORD code_page_;
language()
{
language_
= 0;
code_page_ = 0;
}
}
;
}

class version
{
public:
version()
{
// Get application name
TCHAR buf[MAX_PATH] = "";
if
(::GetModuleFileName(0, buf, sizeof(buf)))
{
std::
string app_name = buf;
app_name = app_name.substr(app_name.rfind("\\") + 1);
// Get version info
DWORD h = 0;
DWORD resource_size = ::GetFileVersionInfoSize(const_cast<char*>(app_name.c_str()), &h);
if
(resource_size)
{
resource_data_
= new unsigned char[resource_size];
if
(resource_data_)
{
if(::GetFileVersionInfo(const_cast<char*>(app_name.c_str()),
0,
resource_size,
static_cast<LPVOID>(resource_data_)) != FALSE)
{
UINT size
= 0;
// Get language information
if(::VerQueryValue(static_cast<LPVOID>(resource_data_),
"\\VarFileInfo\\Translation",
reinterpret_cast<LPVOID*>(&language_information_),
&size)
== FALSE)
throw std::exception("Requested localized version information not available");
}
else
{
std::stringstream exception
;
exception << "Could not get version information (Windows error: " << ::GetLastError() << ")";
throw
std::exception(exception.str().c_str());
}
}
else
throw
std::bad_alloc();
}
else
{
std::stringstream exception
;
exception << "No version information found (Windows error: " << ::GetLastError() << ")";
throw
std::exception(exception.str().c_str());
}
}
else
throw
std::exception("Could not get application name");
}
~version() {
delete [] resource_data_; }
std::
string get_product_name() const { return get_value("ProductName"); }
std::
string get_internal_name() const { return get_value("InternalName"); }
std::
string get_product_version() const { return get_value("ProductVersion"); }
std::
string get_special_build() const { return get_value("SpecialBuild"); }
std::
string get_private_build() const { return get_value("PrivateBuild"); }
std::
string get_copyright() const { return get_value("LegalCopyright"); }
std::
string get_trademarks() const { return get_value("LegalTrademarks"); }
std::
string get_comments() const { return get_value("Comments"); }
std::
string get_company_name() const { return get_value("CompanyName"); }
std::
string get_file_version() const { return get_value("FileVersion"); }
std::
string get_file_description() const { return get_value("FileDescription"); }
private:
unsigned char *resource_data_;
version_nmsp::language *language_information_;
std::string get_value(const std::string &key) const
{
if(resource_data_)
{
UINT size
= 0;
std::stringstream t;
LPVOID value = 0;
// Build query string
t << "\\StringFileInfo\\" << std::setw(4) << std::setfill('0') << std::hex
<< language_information_->language_ << std::setw(
4) << std::hex
<< language_information_->code_page_ <<
"\\" << key;

if
(::VerQueryValue(static_cast<LPVOID>(resource_data_),
const_cast<LPTSTR>(t.str().c_str()),
static_cast<LPVOID*>(&value),
&size) !
= FALSE)
return static_cast<LPTSTR>(value);
}
return "";
}
}
;

#endif


The above class can be used as follows:

#include <iostream>
#include <version.hpp>
#include <conio.h>

int main()
{
try
{
version v
;
std::cout << v.get_product_name() << std::endl;
}
catch(const std::exception& e)
{
std::cerr << e.what() << std::endl
;
}

_getch()
;

return
0;
}

Note: Most of the material in this article is taken from codeguru.com


Recommended Reading :

Windows SDK : How to get the application directory, system directory and windows directory?

Q: How to get the application directory?

A:

// With CString
char szAppPath[MAX_PATH] = _T("");
CString strAppDirectory;

::GetModuleFileName(0, szAppPath, sizeof(szAppPath) - 1);

// Extract directory
strAppDirectory = szAppPath;
strAppDirectory = strAppDirectory.Left(strAppDirectory.ReverseFind(_T('\\')));

 

Q: How to get the system directory?

A:

TCHAR szDirectory[MAX_PATH] = "";
UINT Bytes = ::GetSystemDirectory(szDirectory, sizeof(szDirectory));
if
(!Bytes)
// Error -> call '::GetLastError()'
else if(Bytes > sizeof(szDirectory))
// Buffer too small
else
// Success

Q: How to get the windows directory?
A:

TCHAR szDirectory[MAX_PATH] = "";
UINT Bytes = ::GetWindowsDirectory(szDirectory, sizeof(szDirectory));
if
(!Bytes)
// Error -> call '::GetLastError()'
else if(Bytes > sizeof(szDirectory))
// Buffer too small
else
// Success

 

Note: Most of the material in this article is taken from codeguru.com


Recommended Reading :

Windows SDK Application: How to Get &amp; set the current working directory?

Q: How to set the current working directory?

A:

if(::SetCurrentDirectory("c:\\test") == FALSE)
// Error -> call 'GetLastError()'

 

Q: How to get the current working directory?
A:

TCHAR szDirectory[MAX_PATH] = "";

if
(!::GetCurrentDirectory(sizeof(szDirectory) - 1, szDirectory))
// Error -> call '::GetLastError()'

Q: How to get Application Data path in user profile directory?
A:

BOOL GetAppDataPath(CString &sAppDataPath)
{
TCHAR path[_MAX_PATH] = {0};
if
(GetEnvironmentVariable(_T("APPDATA"), path, _MAX_PATH))
{
sAppDataPath
= path;
return TRUE;
}
else
{
sAppDataPath
= _T("");
return FALSE;
}
}

Q: How to get User Profile path (if available in environment)?
A:

BOOL GetUserProfilePath(CString &sAppDataPath)
{
TCHAR path[_MAX_PATH] = {0};
if
(GetEnvironmentVariable(_T("USERPROFILE"), path, countof(path)))
{
sAppDataPath
= path;
return TRUE;
}
else
{
sAppDataPath
= _T("");
return FALSE;
}
}

 

Note: Most of the material in this article is taken from codeguru.com


Recommended Reading :

Visual C++ Application: How to get the applications name?

Q: How to get the application name?
A: If this is a MFC application you could do

AfxGetApp()->m_pszExeName;


In all other cases the function 'GetModuleFileName()' can be used...

// With CString
TCHAR szAppPath[MAX_PATH] = _T("");
CString strAppName;

::GetModuleFileName(0, szAppPath, MAX_PATH);

// Extract name
strAppName = szAppPath;
strAppName = strAppName.Right(strAppName.ReverseFind(_T('\\')) + 1);

 

Note: Most of the material in this article is taken from codeguru.com


Recommended Reading :

Windows SDK: How to get the reason for a failure of a SDK function?

Q: How to get the reason for a failure of a SDK function?
A: First of all, take a look in MSDN and read the documentation of the function. See the meaning of the returned value.

Most Windows SDK functions return a value showing if the function succeeded or failed (in our example 0 if failed and nonzero if succeeded).

Usually, next is written in MSDN: To get extended error information, call 'GetLastError()'.

BOOL bRet = CreateDirectory(_T("X:\\MyApp\\Bin\\Shared"), NULL);
if
(!bRet)
{
DWORD dwError
= GetLastError();
// put a breakpoint here and type dwError in Error Lookup tool
}

Also, we can get the error text using 'FormatMessage()':

void ReportLastError()
{
LPCTSTR pszCaption
= _T("Windows SDK Error Report");
DWORD dwError = GetLastError();
if
(NOERROR == dwError)
{
MessageBox(
NULL, _T("No error"), pszCaption, MB_OK);
}
else
{
const DWORD dwFormatControl = FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_FROM_SYSTEM
;

LPVOID pTextBuffer = NULL;
DWORD dwCount = FormatMessage(dwFormatControl,
NULL,
dwError,
0,
(LPTSTR) &pTextBuffer,
0,
NULL);
if
(0 != dwCount)
{
MessageBox(
NULL, (LPCSTR)pTextBuffer, pszCaption, MB_OK|MB_ICONERROR);
LocalFree(pTextBuffer);
}
else
{
MessageBox(
NULL, _T("Unknown error"), pszCaption, MB_OK|MB_ICONERROR);
}
}
}

The following example shows how to use it:

BOOL bRet = CreateDirectory(_T("X:\\MyApp\\Bin\\Shared"), NULL);
if
(!bRet)
{
ReportLastError()
;
}

 

Note: Most of the material in this article is taken from codeguru.com


Recommended Reading :




Bankruptcy - Debt Consolidation - Credit Cards - Arizona Landscaping