Click here to Skip to main content
11,790,385 members (62,708 online)
Click here to Skip to main content
Add your own
alternative version

Scoped Handle - "Smart pointer" for Windows objects

, 21 Jul 2010 CPOL 21.3K 137 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);

    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.


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


About the Author

Miki Rozloznik
Software Developer (Senior) Eccam s.r.o.
Czech Republic Czech Republic
Senior Sofware Developer focused on embedded systems.
Company website:

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.1509028.1 | Last Updated 21 Jul 2010
Article Copyright 2010 by Miki Rozloznik
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid