3

Can anybody please tell me how I can get the desktop path(environment variable) using C language commands.

Scenario is that I want to save a file on desktop.What I can do is just to give a fixed desktop path and a filename to save the file. But after giving this fixed path ,my code will become rigid and will not work on anyother computer having different desktop path (environment variable). My question is can I make my code generalize which can work on any windows based machine by capturing the environment variable of desktop , using C language?

Regards

mgiuca
  • 20,958
  • 7
  • 54
  • 70
Asad
  • 521
  • 2
  • 13
  • 30

2 Answers2

10

SHGetSpecialFolderPath(CSIDL_DESKTOP)

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
3

You can use the function getenv() to access environment variables:

The value of an environment variable can be accessed with the getenv function. This is declared in the header file stdlib.h.

For Windows systems, USERPROFILE should be good if you append \Desktop to it (see the link provided by mgiuca, for example). Note that the path will contain spaces in most cases, so handle it accordingly.

Also, using environment variables to get the path of the desktop folder isn't the best way and might not work in some cases (also see other SO answers to this topic, like this one), so see this answer as an answer to your specific question, especially for the "environment variables in C++" part.

Community
  • 1
  • 1
schnaader
  • 49,103
  • 10
  • 104
  • 136
  • 2
    +1. I was about to say the same thing and I found a source recommending that approach [here](http://www.wilsonmar.com/1envvars.htm). (Search that page for "Desktop".) – mgiuca Mar 16 '11 at 01:27
  • 4
    @schnaader, @mgiuca: There's a lot of bad advice out on the Internet. Using `%USERPROFILE%\Desktop` for the desktop path is an example. – Ben Voigt Mar 16 '11 at 01:32
  • Environment variables are not guaranteed to be defined in all scenarios. They are mainly a nicety for you but from programs use the APIs. – Joey Mar 16 '11 at 01:33
  • @Ben, Joey: OK, edited my answer to point this out. @Joey: I'm curious, if the environment variable isn't defined, it will be empty, so we at least can detect cases where it won't work and handle this, right? – schnaader Mar 16 '11 at 01:39
  • So if unreliable method A fails, you fall back to the always-reliable method B? Why bother with method A at all then? – tenfour Mar 16 '11 at 01:44
  • @tenfour: No, I asked this for cases where you don't have a method B. For example, you won't be able to call API functions in batch files. – schnaader Mar 16 '11 at 01:47
  • @schnaader: The question is tagged `c`, it says `C` in the title. There is no reason to limit oneself to batch files all of a sudden. – Joey Mar 16 '11 at 10:59
  • @Joey: Yes, I'm aware it's very off-topic. I'll investigate some more and perhaps ask a seperate question. – schnaader Mar 16 '11 at 11:37