Click here to Skip to main content
Click here to Skip to main content

A handy class to make use of Windows Registry

, 15 Aug 2004
Rate this:
Please Sign up or sign in to vote.
Shows how simple accessing Windows Registry can be if you do not need bells and whistles.

Sources update

The sources have been updated. (Hopefully) This will make them compilable on VC 7+. I couldn't test it with VC 7, but I expect it will be OK now. For more info take a look what was the problem.

New Additions

This class has been modified:

  • Improved internal logic.
  • Improved support for writing structured data to registry.
  • Added possibility to see internal execution flow (e.g., when data is read from and written to the registry).
  • Added support for HKEY_LOCAL_MACHINE, HKEY_USERS, and all the others...

In short, in order to store a structure in registry, you only need to do like this:

SomeStruct X;
//set struct values...
reg["SomeStructData"].set_struct(X);

In order to read back the stored structure:

SomeStruct X;
//set struct values...
if(reg["SomeStructData"].get_struct(X)){
    //Ok, X contains the read data...
}else {
    //error reading struct.
}

In order to use HKEY_LOCAL_MACHINE or other, you can pass a second parameter of type registry::Key to the registry constructor:

registry reg("Sowtware\\Whatever",registry::hkey_local_machine);

The second parameter is optional, it defaults to registry::hkey_current_user.

In order to see internal execution flow, you may #define WANT_TRACE. And in console mode, you'll see when and what objects are created, and when values read to/ written from the registry. There was added a new project with_trace to see that.

//with trace

#define WANT_TRACE //define this to be able to see internal details...

#include "registry.h"
#include "string.h"
#include <STRING>

struct Something{
    int area;
    float height;
};

int main(int, char*)
{
    registry reg("Software\\Company");
    {
        Something X;
        X.area=100;
        X.height=4.5;

        reg["Something"].set_struct(X);
    }
    Something Z;
    if(reg["Something"].get_struct(Z)){
        printf("area is: %i\nheight is: %f\n", Z.area,Z.height);
    }

    return 0;
}

It produces the following output:

with_trace output

Introduction

First of all, you need only one file registry.h, that's included in the source distribution. Read on...

//Dirty and fast howto

#include "registry.h"
#include "string.h"

int main(int, char*){

    registry reg("Software\\Company");
    reg["Language"]="English";        //set value
    reg["Width"]=50;
    printf("The address is: %s\n",(char*)reg["Address"]); 
    //prints nothing unless you put something in
    return 0;
}

A more descriptive howto:

//Long story:

#include "registry.h"
#include "string.h"

struct ServerAddress{
    char name[64];
    char ip[15];
    short port;
};

int main(int,char*){

    //first step is to create our home registry 
    //record(or open it if exists)
    //the constructor accepts a string and if you do:
    registry settings("Software\\MyCoolApp");
    //you open HKEY_CURRENT_USER\Sowtware\MyCoolApp

    //Due to simplicity this class is desined to deal with only 
    //HKEY_CURRENT_USER registry group. 
    //You may, however, modify this behavior if you need

    //To make sure that the home key has been created or 
    //opened you can test it like this:

    if(!settings){
        //error code goes here...
        exit(1);
    }

    //The next step is to create (or open if exists) 
    //a value key:
    //the official way is like this: (for another, 
    //simpler way, read below.)

    registry::iterator lang=settings["Language"];    
    //Personally I don't use it this way - too much to type...

    //and then you can retrive value of "Language" key 
    //as follows:

    printf("The selected language is: \"%s\"\n",(char*)lang);

    //if you want to modify a value you can do simply like this:

    lang="Russian";

    //Internally this class stores values as 
    //binary data and therefore 
    //you are not limited to strings only.

    // Example:

    ServerAddress MyCoolServer;
    strcpy(MyCoolServer.name,"somewhere.example.com");
    strcpy(MyCoolServer.ip,"192.168.0.1");
    MyCoolServer.port=1024;

    //now let's put this record into registry key "server"
    //it can be simply done like this:

    registry::iterator server=settings["server"];
    server=string((const char *)(&MyCoolServer),sizeof(MyCoolServer));

    //now let's test by retriving the structure back:

    ServerAddress serAdr;
    const string &FromRegistry=server;
    //copy data only if it's of the size of the struct ServerAddress
    if(FromRegistry.length()==sizeof(ServerAddress)){        
        memcpy(&serAdr,FromRegistry.c_str(), sizeof(ServerAddress));
        //now let's see what we have (see a pic below):
        printf("Print out for my server:\n");
        printf("\tserver's host name is:  %s\n",    serAdr.name);
        printf("\tserver's ip address is: %s\n",    serAdr.ip);
        printf("\tserver's port is:       %u\n\n",  serAdr.port);
    }else{
        //error code goes here...
    }
    return 0;
}

Sample Image - long_story.jpg

Pic.1 Output from a more descriptive howto.

I coded these few lines with simplicity in mind. I like the style, when I can assign value to a registry key as to a usual variable. I will describe shortly how I use this code in my projects. I put a member variable reg (instance of registry) to my app's class (there is a reason, read below) that needs access to the registry. Then, in the class' constructor, I instantiate reg variable to the registry home key. Since there is no default constructor in the registry class, you may do it like this:

class my_app{
protected:
    registry reg;
    string UserName;
public:
    my_app() : reg("Software\\my_app"){ // <--
        UserName = reg["UserName"]; //read value
    }
    ~my_app(){
        //store value back to the registry
        reg["UserName"] = UserName;
    }
}

In the preceding line, you actually don't need to create a separate string for UserName - you may have a member variable of registry::iterator type, that will be automatically stored to the registry when your class is destructed (see the final example at the bottom of the page).

And then, whenever you need, you can do like this:

SetLanguage(reg["Lang"]); 
string UserName=reg["User"];

that's really simple...

Background

Now, a little background on how it works internally. This is actually a very lightweight class. It makes less API calls than you would probably do.

For example, the line:

reg["Something"]="nothing";

will only once physically access registry on destruction of the returned key-value to assign value "nothing" to key "something".

Same happens with the next lines (only one API call when the group goes out of scope):

registry::iterator name=settings["UserName"];
name="John";
name="Alex";
name="Someone Else";

Basically, if you intend to use this class, you should be aware that statement reg["something"]="nothing"; doesn't modify anything in registry by itself. The value will be set only when the statement goes out of scope, like this:

{
    reg["UserName"]="Bill";
    printf("The username is: %s\n", (char*)reg["UserName"]); 
    //!!WILL NOT PRINT BILL, 
    //it will print the value that was before the previous line
}//at this point the value Bill is in the registry
printf("The username is: %s\n", (char*)reg["UserName"]); //now it prints Bill;

In order to force it to commit to the registry at some point, you can use flush() method like this:

registry::iterator name=settings["UserName"];
name="John";
name.flush(); //at this point it will write value "John" to registry.

The same applies to reading values - they are retrieved only when you request them, and only once! So, if you know (or think) that something else (perhaps Earth's magnetic field Smile | :) ) has modified a key's value, you may use refresh() method. But, be carfull!! Anything you have assigned before will not be committed (it's overwritten by the returned value from registry).

And a very important point. When the instance of registry is destructed, or goes out of scope, then all the values you created from it will not have access to the registry. That is, all iterators on a given registry instance should be destructed before their parent registry instance. That's why I use this class as a member of another class. When the parent class is destroyed, it doesn't need access to the registry, neither is it possible at that point.

That's it. Hope it will be useful to someone.

A better example

#include "registry.h"
#include <iostream>


class my_app{
protected:
    registry reg;
    registry::iterator UserName;
public:
    my_app():reg("Software\\Company"),UserName(reg["UserName"]){}
    ~my_app(){}
    void SetUserName(const char * name){
        UserName = name;
    }
    const char * GetUserName(){
        return (const char *) UserName;
    }
};

int main (int, char *){
    my_app App;
    App.SetUserName("Alex");
    cout<<"The username is: "<<App.GetUserName()
        <<endl<<"Thanks for playing..."<<endl;
    return 0;
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

__PPS__

Canada Canada
Big Grin | :-D

Comments and Discussions

 
Generalnumber of values in a key PinmemberMbarki26-Apr-07 0:33 
GeneralRe: number of values in a key Pinmember__PPS__27-Apr-07 13:20 
GeneralSource does not work with STLPORT PinmemberRalfGriggel27-Nov-06 5:39 
GeneralRe: Source does not work with STLPORT Pinmember__PPS__27-Nov-06 6:57 
Generalsources not working on restricted user Pinmemberdimmudimmu17-Mar-06 1:51 
GeneralRe: sources not working on restricted user Pinmember__PPS__17-Mar-06 5:32 
I don't even remember how it works, it's been a long time as I wrote this piece of code. However, as far as I remember

registry reg("Sowtware\\Whatever");

 
will open current_user and not local machine, so it's supposed to work this way. Once you need to read values from local_machine then they will not be read if they have any restrictions, since in this implementation the simplest way is used - every key is open with KEY_ALL_ACCESS flag. And the key cannot be opened with this flag for restricted keys.
 
One possible solution would be to write const and non-const protected functions, so that const versions open keys in read_only mode and do not try to modify them and then for read only you would need to:

const registry reg("Sowtware\\Whatever", hkey_local_machine);

 
which then would had to use const function that would open keys in read only mode... You would need to play with mutable data and const function to make things work correctly. As I don't remember how everything works I don't want to modify it, you may try to do it, it's very easy task.
GeneralUNICODE support PinmemberCrystalPaul8-Dec-05 18:29 
GeneralRe: UNICODE support Pinmember__PPS__8-Dec-05 23:32 
GeneralSetting default value on first use. Pinmemberneticous13-Jun-05 20:31 
GeneralRe: Setting default value on first use. Pinmemberneticous14-Jun-05 4:01 
Generalreally great, just one thing missing... PinsussTiago10-Nov-04 6:28 
Generalreally easy to use, great article! thanks pps PinmemberRobert Space15-Sep-04 0:30 
GeneralRe: really easy to use, great article! thanks pps PinmemberRobert Space15-Sep-04 0:43 
GeneralRe: really easy to use, great article! thanks pps Pinmember__PPS__15-Sep-04 14:39 
GeneralMain doesnt compile PinmemberCRWeaks2312-Aug-04 10:12 
GeneralRe: Main doesnt compile PinsussAnonymous14-Aug-04 18:12 
GeneralRe: Main doesnt compile Pinmember__PPS__14-Aug-04 19:46 
GeneralImplementation details PinmemberJohann Gerell14-Jun-04 2:22 
GeneralRe: Implementation details Pinmember__PPS__14-Jun-04 2:34 
GeneralRe: Implementation details PinmemberJohann Gerell14-Jun-04 4:02 
GeneralRe: Implementation details Pinmember__PPS__14-Jun-04 5:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141220.1 | Last Updated 16 Aug 2004
Article Copyright 2004 by __PPS__
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid