Expanding Environment Variables

This is a discussion on Expanding Environment Variables within the C Programming forums, part of the General Programming Boards category; I am trying to get the path of the system root directory by using %SystemRoot% in C code. What I ...

  1. #1
    Registered User
    Join Date
    Nov 2007
    Posts
    2

    Expanding Environment Variables

    I am trying to get the path of the system root directory by using %SystemRoot% in C code. What I originally had was:

    Code:
    TCHAR szBuf[1024];
    wsprintf(szBuf, L"c:\\windows\\system32\\myapp.exe \r\n");
    WriteLogFile(szBuf);
    Now, I want to grab the system root directory at runtime and use that instead of hardcoding in the location as on win2k, the path is "c:\winnt" or people may have installed their os on a different drive.

    I know in c++ or in c# you can use the Environment.ExpandEnvironmentVariables Method.
    Code:
    String query = "My system drive is %SystemDrive% and my system root is %SystemRoot%";
    String  str = Environment.ExpandEnvironmentVariables(query);
    
    This will give an output of something like: "My system drive is C: and my system root is C:\WINNT"
    Is there something similar in c that I can use?

  2. #2
    Ex scientia vera
    Join Date
    Sep 2007
    Posts
    478

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Or, if you actually want to expand environment variables in general, you can use getenv(), e.g.
    Code:
        printf("System directory: %s\n", getenv("SystemRoot"));
    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  4. #4
    Registered User
    Join Date
    Nov 2007
    Posts
    2
    Thanks for the suggestions! I was able to get it working like so...

    Code:
    TCHAR szBuf[1024];
    TCHAR szMyApp[1024];
    wchar_t systemrootpath[64]= L"";
    wchar_t dname[64]=L"";
    
    ...
    
    wsprintf(szBuf, L"%s", getenv("SystemRoot"));
    mbstowcs(systemrootpath, szBuf, 64);  // Convert to unicode
    
    wsprintf(szMyApp,L"%s\\system32\\myapp.exe %s\0", systemrootpath, dname);
    
    ...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. esbo's data sharing example
    By esbo in forum C Programming
    Replies: 49
    Last Post: 01-08-2008, 10:07 PM
  2. Global Variables
    By Taka in forum C Programming
    Replies: 34
    Last Post: 11-02-2007, 03:25 AM
  3. Replies: 2
    Last Post: 04-28-2007, 01:05 PM
  4. functions to return 2 variables?
    By tim in forum C Programming
    Replies: 5
    Last Post: 02-18-2002, 01:39 PM
  5. What are environment variables?
    By Nutshell in forum A Brief History of Cprogramming.com
    Replies: 4
    Last Post: 02-18-2002, 07:11 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21