Main Page   Modules   File List   Related Pages   Examples  

Edit Registry via Program Regedit

Apart from editing the registry via Windows API functions, it can also be done with program regedit. Here is an example of how you may do that.

/*
 * For instructional purposes.
 *
 * Here is a version to edit the registry using program regedit.
 *
 * commandline: regedit /s file.reg
 *
 * for example, to create variable rulbus with contents isa, and remove
 * variable sublur, file.reg may contain (without the linenumbers):
 *
 * 1 REGEDIT4
 * 2
 * 3 [HKEY_CURRENT_USER\Environment]
 * 4 "rulbus"="isa"
 * 5 "sublur"=-
 */

#include "tools.h"
#include <string>
#include <process>

using namespace std;

static int writeRegEnv ( const string& name, const string& value,
                           int optcu = 0, int optrm = 0, int optkeep = 0  );

int writeRegEnv( const string& name, const string& value, int optcu /* = 0 */ )
{
   return writeRegEnv ( name, value, optcu, 0, optkeep );
}

int deleteRegEnv( const string& name, int optcu /* = 0 */ )
{
   return writeRegEnv ( name, "", optcu, 1, optkeep );
}

static int writeRegEnv ( const string& name, const string& value,
                           int optcu /* = 0 */, int optrm /* = 0 */, int optkeep /* = 0 */ )
{
   /*
    * open file for registry commands (w+b):
    */

   string regName( basename( NULL ) + string(".reg") );
   FILE *regFile = fopen( regName.c_str(), "w" );

   if ( NULL == regFile )
      return error( E_PS, "cannot open temporary file '%s' with regedit source:", regName.c_str() );

   /*
    * write registry commands in file:
    */

   fprintf( regFile,
      optcu ? "REGEDIT4\n"
              "\n"
              "[HKEY_CURRENT_USER\\Environment]\n"
            : "REGEDIT4\n"
              "\n"
              "[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment]\n"
   );

   fprintf( regFile, optrm ? "\"%s\"=-\n" : "\"%s\"=\"%s\"\n", name.c_str(), value.c_str() );

   /*
    * close file with registry commands:
    */

   if ( EOF == fclose( regFile ) )
      return error( E_PS, "cannot close temporary file '%s' with regedit source:", regName.c_str() );

   /*
    * edit registry, using: regedit /s {file}
    */

   int status = spawnlp ( P_WAIT, "regedit", "regedit", "/s", regName.c_str(), NULL );

   if      ( status < 0 ) return error( E_PS, "spawn of regedit failed:" );
   else if ( status > 0 ) return error( E_PS, "regedit returned error"   );

   /*
    * remove file with registry commands, unless option -k is specified:
    */

   if ( !optkeep && remove( regName.c_str() ) )
      return error( E_PS, "cannot remove temporary file '%s' with regedit source:", regName.c_str() );

   return E_OK;
}



Generated on Tue Apr 29 11:20:46 2003 for Edit Env by doxygen 1.3