Reputation: 13
I have been unable to open the file. The fb.is_Open()
never returns true. Only when I hard code the data source in the fb.open()
it works.
I've tried converting it to a string
, char
, and wstring
with no effect.
What am I missing? The correct code would be fantastic but also and explanation.
Trying to open a file with the data source variable:
wchar_t dataSource[2048];
DWORD errNum = GetModuleFileName(NULL, dataSource, sizeof(dataSource)); //get current dir.
ifstream fb;
wcscat_s(dataSource, L".confg"); //adds ".config" to get full data Sournce
fb.open(dataSource, ios::in);
if (fb.is_open())
{
//get information
}
fb.close();
Here are some things Ive tried that have not worked: wstring x = dataSource; x.c_str()
char* cnvFileLoc = (char*)malloc(2048);
size_t count;
count = wcstombs_s(&count, cnvFileLoc, 2048, dataSource, 2048);
what does work is: fb.open(X:\CPP.Lessons\PluralSight\PluralSight.Fundamentals\Debug\PluralSight.Fundamentals.exe.config, ios::in)
Upvotes: 0
Views: 612
Reputation: 595897
Your call to GetModuleFileName()
is wrong. The last parameter is expressed in characters, not in bytes, and the return value tells how many characters were copied:
wchar_t dataSource[2048];
if (GetModuleFileName(NULL, dataSource, 2048) > 0)
{
...
}
Or:
wchar_t dataSource[2048];
if (GetModuleFileName(NULL, dataSource, sizeof(dataSource)/sizeof(dataSource[0])) > 0)
{
...
}
Or:
wchar_t dataSource[2048];
if (GetModuleFileName(NULL, dataSource, _countof(dataSource)) > 0)
{
...
}
Or:
wchar_t dataSource[2048];
if (GetModuleFileName(NULL, dataSource, ARRAYSIZE(dataSource)) > 0)
{
...
}
That being said, you are appending .confg
to the end of the full filename. So, if your application is named myapp.exe
, you are trying to open myapp.exe.confg
. Is that what you really want?
If yes, then make sure the .confg
file actually exists, and that your app has permission to access it. CreateFile()
would offer much more useful error info then ifstream
does.
Otherwise, assuming the .confg
file is at least in the same folder as your app, you would have to manually remove the filename portion from the buffer and then substitute in the correct filename. Have a look at PathRemoveFileSpec()
and PathCombine()
for that. Or, if the file is named myapp.confg
, look at PathRenameExtension()
.
Update: I just noticed that your code is appending .confg
, but your comment says .config
instead:
//wcscat_s(dataSource, L".confg");
wcscat_s(dataSource, L".config");
Upvotes: 4
Reputation: 41301
You may have mistyped the file extension: L".confg"
instead of L".config"
as stated by the comment in your code.
Upvotes: 4