Posted By

jimfred on 02/18/09


Tagged

c windows


Versions (?)

Get current working directory


 / Published in: C
 

URL: http://www.pages.drexel.edu/~mfp27/cppfaqs/

Sometimes I want a complete path to a file in the current working directory to make error messages clearer. The URL has alternate approaches.

  1. // Using MFC.
  2. CString cwd;
  3. DWORD cwdLen = ::GetCurrentDirectory( MAX_PATH, cwd.GetBufferSetLength(MAX_PATH+1) );
  4. cwd.ReleaseBuffer( cwdLen ); // Note that ReleaseBuffer doesn't need a +1 for the null byte.
  5.  
  6. // Alternate approach, in C, using Win API.
  7. static LPCSTR GetDefaultDirectory()
  8. {
  9. static TCHAR szDirectory[MAX_PATH] = {0}; // place to remember path found.
  10.  
  11. if ( !szDirectory[0] ) // if already found.
  12. {
  13. ::GetCurrentDirectory(sizeof(szDirectory) - 1, szDirectory); // in winbase.h
  14. }
  15.  
  16. return szDirectory;
  17.  
  18. }

Report this snippet  

You need to login to post a comment.