Click here to Skip to main content
15,885,216 members
Articles / Programming Languages / C++

Scoped Handle - "Smart pointer" for Windows objects

Rate me:
Please Sign up or sign in to vote.
4.33/5 (6 votes)
21 Jul 2010CPOL2 min read 43.7K   226   8  
Introduces a scoped handle template class to call delete handle methods automatically.
/***************************************************************************************************************
 *
 * Filename: ScopedHandleExample.cpp
 * 
 * Author:   Miki Rozloznik
 *
 * Date:     2010/07/21
 *
 * Implementation Description:
 *//** \file 
 *   The example of usage of scoped handle for Windows objects.
 *//*
 *
 **************************************************************************************************************/

#include <windows.h>
#include <tchar.h>

#include "ScopedHandle.h"

int _tmain(int argc, _TCHAR* argv[])
{
    // open some file
    const _TCHAR* pFileName = _T("c:\\windows\\Coffee Bean.bmp");
    FileScopedHandle File( CreateFile(pFileName, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
                                      NULL) );
    if (!File)
    {
        OutputDebugString(_T("File open failure!\n"));
        return -1;
    }

    // get file size in bytes
    const DWORD FileSize = GetFileSize(File.Get(), NULL);
    if (FileSize == INVALID_FILE_SIZE)
    {
        OutputDebugString(_T("File has unknown size!\n"));
        return -1;
    }

    // print result
    const unsigned int MaxMessageLen = 64;
    _TCHAR Message[MaxMessageLen + 1];
    Message[MaxMessageLen] = 0;
    _sntprintf(Message, MaxMessageLen, _T("The file %s contains %ld bytes.\n"), pFileName, FileSize);
    OutputDebugString(Message);

    return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Eccam s.r.o.
Czech Republic Czech Republic
Senior Sofware Developer focused on embedded systems.
Company website: http://www.eccam.com

Comments and Discussions