简体   繁体   中英

Windows up one directory from current path

I have been searching for hours but cant find a solution to this as yet. Apologies it is probably really simple.

My program is using CreateDirectory to create a new directory and then set the path to it to receive a number of data files:

if (CreateDirectory(dateTime.c_str(), NULL) || ERROR_ALREADY_EXISTS == GetLastError())
{
    SetCurrentDirectory(dateTime.c_str());
}

Once all the data files have been generated I would like to move back up one directory without specifying the absolute path. Something equivalent to cd.. or ../ Does anyone know the best way to do this?

One possible approach is to get the current directory ( GetCurrentDirectory ) before changing to a new one and once complete, then change back the desired directory; akin to a push/pop.

In the sample I've left out error checking and buffer size requirements for simplicity.

TCHAR resetDir[1024] = {};
GetCurrentDirectory(1024, resetDir);
//... Do some work, change directories etc...
// Reset the directory
SetCurrentDirectory(resetDir);

Side note: the current directory when the process is launched is not necessarily the same as the directory the process image is in (the exe path).

Relative changes can be done with a simple

SetCurrentDirectory(_T(".."));

Although basing the relative from the current directory would also work (and may be preferable);

SetCurrentDirectory((currentDir + _T("\\..")).c_str());

Internally, cd command ends using SetCurrentDirectory . So to get something equivalent to cd.. or cd ../ you can simply use:

cr = ::SetCurrentDirectory("..");

cr should be non zero if it succeded and 0 if it failed. In the latter case use GetLastError to get further information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM