问题
I have a C++ program that takes user input for fopen
in order to initiate a file write. Could someone help me find a function which will return a FILE*
and use the Windows specific version of mkdir
in order to create the folder structure for fopen
to never fail to open a new file in the specified location because one of the folders does not exist. Thanks a bunch!
回答1:
there's a method MakeSureDirectoryPathExists in the windows API, declared in dbghelp.h. It recursively creates directories, so I guess that's what you are after. However, there is NO way of making sure this 'never fails' as you ask, as it also depends on privileges etc if you have write access to a certain directory.
edit: here's some dummy sample code; it uses GetProcAddress though, as I couldn't find the dbghelp header when I wrote it.
typedef BOOL (WINAPI * CreateDirFun ) ( __in PCSTR DirPath );
HMODULE h = LoadLibrary( "dbghelp.dll" );
CreateDirFun pFun = (CreateDirFun) GetProcAddress( h, "MakeSureDirectoryPathExists" );
(*m_pFun)( psPath ) )
CreateDirectory( psPath );
FreeLibrary( h );
来源:https://stackoverflow.com/questions/2834737/creating-new-folders-if-they-dont-exist-for-fopen