Creating new folders if they don't exist for f

2019-08-02 19:02发布

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条回答
Lonely孤独者°
2楼-- · 2019-08-02 19:20

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 );
查看更多
登录 后发表回答