tags:

views:

85

answers:

4

As above, how do I get the AppData folder in Windows using C?

I know that for C# you use Environment.SpecialFolder.ApplicationData

+2  A: 

If I recall correctly it should just be

#include <stdlib.h>
getenv("APPDATA");

Edit: Just double-checked, works fine!

GigaWatt
Use the proper API instead, as environment variables on Windows are more a courtesy than a contract. They might not be present under all circumstances. However, `SHGetKnownFolderPath` *will* give you the path every time.
Joey
But SHGetKnownFolderPath might not be available either. Tough cookies.
Hans Passant
@Hans: SHGetSpecialFolderPath should be, though. Depending on the OS one targets.
Joey
+4  A: 

Use SHGetSpecialFolderPath with a CSIDL set to the desired folder (probably CSIDL_APPDATA or CSIDL_LOCAL_APPDATA).

You can also use the newer SHGetFolderPath() and SHGetKnownFolderPath() functions. There's also SHGetKnownFolderIDList() and if you like COM there's IKnownFolder::GetPath().

Ferruccio
Note that this function was superseded twice already. You might as well give the other two (including the current and recommended function).
Joey
@Joey - I had not realized that. Thanks.
Ferruccio
A: 

You might use these functions:

#include <stdlib.h>
char *getenv( 
   const char *varname 
);
wchar_t *_wgetenv( 
   const wchar_t *varname 
);

Like so:

#include <stdio.h>
char *appData = getenv("AppData");
printf("%s\n", appData);
Matt Joiner
Use the proper API instead, as environment variables on Windows are more a courtesy than a contract. They might not be present under all circumstances. However, `SHGetKnownFolderPath` *will* give you the path every time.
Joey
+1  A: 

Using the %APPDATA% environment variable will probably work most of the time. However, if you want to do this the official Windows way, you should use use the SHGetFolderPath function, passing the CSIDL value CSIDL_APPDATA or CSIDL_LOCAL_APPDATA, depending on your needs.

This is what the Environment.GetFolderPath() method is using in .NET.

EDIT: Joey correctly points out that this has been replaced by SHGetKnownFolderPath in Windows Vista. News to me :-).

Matt Solnit