Possible Duplicate:
c++ how to create a directory from a path
I'm trying to create an .ini file in the application data folder so I can use settings. I gave it a try, but I couldn't figure out how to check if it already exists, and if not, create the subdirectory and .ini file.
When I get the last error message it says "The system cannot find the path specified."
#include <string>
using namespace std;
#include <Windows.h>
#include <Shlwapi.h>
#include <ShlObj.h>
#pragma comment(lib, "shlwapi.lib")
namespace Settings
{
CIni Ini;
bool Available = false;
char Directory[MAX_PATH];
const char *IniFileName = "Settings.ini";
void CheckError() {
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&lpMsgBuf, 0, NULL
);
string msg = (LPTSTR)lpMsgBuf;
Error(msg); // MessageBox
}
void Initialize() {
// Get AppData directory
if (SHGetFolderPath(0, CSIDL_COMMON_APPDATA, 0, 0, Directory) >= 0) {
string fullpath;
string subDir = "\\MyCompany\\MyProgram\\1.0\\";
PathAppend(Directory, subDir.c_str());
fullpath = Directory;
fullpath += IniFileName;
// If directory doesn't exist, create it.
DWORD attrib = GetFileAttributes(Directory);
if (!(attrib != INVALID_FILE_ATTRIBUTES && (attrib & FILE_ATTRIBUTE_DIRECTORY))) {
if (CreateDirectory(Directory, NULL)) {
HANDLE file = CreateFile(
fullpath.c_str(), GENERIC_WRITE, 0, 0,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0
);
if (file != INVALID_HANDLE_VALUE) {
CloseHandle(file);
} else {
CheckError();
return;
}
} else {
CheckError();
return;
}
}
Ini.SetPathName(fullpath.c_str());
Available = true;
}
}
}
I checked and my call to CreateDirectory()
is returning false.
How can I check if the file and directory exists, and if not then create them?