简体   繁体   中英

How to write to temporary folder

I am trying to write a file to the temporary folder, but it is not being executed properly. When I later go in the code to call this, it references the correct location, but says it does not exist. Any Ideas as to what I am doing wrong?

        ofstream fout("%TEMP%\\test.bat"); 
        fout << "cd C:\\Users\\jrowler\\Documents" << endl;
        //Some more fout commands to write to bat
        fout.close();
        wchar_t cmdline[] = L"cmd.exe /C %TEMP%\\test.bat";

if (!CreateProcess(NULL, cmdline, NULL, NULL, false, CREATE_UNICODE_ENVIRONMENT,
        (LPVOID)env.c_str(), NULL, &si, &pi))
    {
        std::cout << GetLastError();
        abort();
    }

Everything works if I am not trying to use the TEMP folder. If I wanted to put it on my desktop, it works perfectly fine. Any ideas why the environment variable does not work correctly when creating, but when trying to create the process, it give me an error that references the correct location specified by the environment variable.

As Retired Ninja points out, you may want to translate the environment variable , if you choose to use an environment variable.

In addition, there are other methods for special folders. In fact, the temp folder has a dedicated function - GetTempPath() .

DWORD const bufferSize = ::GetTempPath(0u, nullptr) + 1u; // get the necessary buffer size
ASSERT(bufferSize);

wchar_t* buffer = new wchar_t[bufferSize];
std::memset(buffer, 0x00, bufferSize);
VERIFY(::GetTempPath(bufferSize, &buffer[0u]));
// [ perform various logic ]
delete[] buffer;

For other special folders, you may choose to use the Shell API.

SHGetFolderPath() and SHGetKnownFolderPath() work well across various versions of windows, wherever the target folder may be located. And there are a tremendous number of folders .

wchar_t folder[MAX_PATH+1];
int const folderId = ... // <-- defined in Shlobj.h

HRESULT const hr = ::SHGetFolderPath(nullptr, folderId, nullptr, SHGFP_TYPE_CURRENT, folder);
if (S_OK != hr)
{
    TRACE("ERROR: Unable to get folder path.");
    return false;
}

// [ perform various logic ]

wchar_t* folder = nullptr;
KNOWNFOLDERID const folderId = ... // <-- defined in KnownFolder.h
HRESULT const hr = ::SHGetKnownFolderPath(folderId, 0u, nullptr, &folder);
if (S_OK != hr)
{
    TRACE("ERROR: Unable to get folder path.");
    return false;
}

// [ perform various logic ]
::CoTaskMemFree(folder);

EDIT: There is an example specifically for creating and using a temp file .

EDIT2: Note that TEMP / TMP environment variables may be slightly different on various systems . However they should be the same value. Look at the 'remarks' section of GetTempPath() to see how the path is determined.

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