• Advertisement
Sign in to follow this  

wofstream to create a file in a folder

This topic is 2160 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi,

I am trying to write a file in a new folder in the %appdata% folder for the current logged in user using a std::wofstream.

I can get the directory for %appdata% and write a file into here, but I am having a problem when trying to make a folder and then put the file I am writing into this folder.

This code works and makes "testdoc.txt" in "C:\Documents and Settings\ME\Application Data"



void main()
{
wofstream BurnDownReport;

BurnDownReport.open(writeToAppData("\\testdoc.txt").c_str());

BurnDownReport << "boom";

BurnDownReport.close();
}

wstring writeToAppData(string filename)
{
std::wstring ws;
TCHAR destination[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, destination))) //use "CSIDL_COMMON_APPDATA" for all users
{
string strPath(destination + filename);

ws.assign(strPath.begin(), strPath.end());

return ws;
}

ws.assign(filename.begin(), filename.end());

return ws;
}



However, when I try this (see change on this line below "BurnDownReport.open(writeToAppData("\\TestFolder\\testdoc.txt").c_str());"), the folder "TestFolder" is not created, and testdoc.txt is not written :




void main()
{
wofstream BurnDownReport;

BurnDownReport.open(writeToAppData("\\TestFolder\\testdoc.txt").c_str());

BurnDownReport << "boom";

BurnDownReport.close();
}


wstring writeToAppData(string filename)
{
std::wstring ws;
TCHAR destination[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, destination))) //use "CSIDL_COMMON_APPDATA" for all users
{
string strPath(destination + filename);

ws.assign(strPath.begin(), strPath.end());

return ws;
}

ws.assign(filename.begin(), filename.end());

return ws;
}




Can you help me please?

Thanks,

Monsunemoon.

Share this post


Link to post
Share on other sites
Advertisement
What makes you think that creating a file stream will automatically create any necessary directories? Remember, if a function isn't clearly documented as doing something, you shouldn't hope that it does it. Even if it did happen to do it, if it isn't documented then this additional behaviour is more likely to become deprecated or even removed.

Unfortunately, standard C++ doesn't really help you much with filesystems. For a close to standard solution, something like these functions in boost::filesystem could be considered.

Alternatively, given that you already have Windows specific code, you can use this function. This function appears to only create one directory at a time, so you would have to write your own function to create a directory tree.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement