Boost logo

Boost :

Subject: Re: [boost] [filesystem] temp_dir_path()
From: Jeff Flinn (TriumphSprint2000_at_[hidden])
Date: 2010-10-09 16:04:29

Jeff Flinn wrote:
> PB wrote:
>> On Sat, Oct 9, 2010 at 5:36 PM, Jeff Flinn
>> <TriumphSprint2000_at_[hidden]> wrote:
>>> The need for portably obtaining 'the' temporary-directory-path has been
>>> brought up a few times(but never addressed AFAICT), and I am now in
>>> the need
>>> for this as well.
>>> Windows has the GetTempPath, which follows a specific order of
>>> looking for a
>>> temporary directory path. If GetTempPath returns 0, GetLastError
>>> provides a
>>> system error.
>>> Posix relies on getEnv("TMPDIR"), which returns 0 if the environment
>>> variable does not exist.

>>> Questions:
>>> - should Posix return an empty path or an error when empty?
>>> - should Windows provide a more 'temp-path' centric error?
>>> - should both verify the path exists?
>>> - if the path does not exist should one be created?
>> A temporary directory getter withing Boost.Filesystem would be a "nice
>> to have". In my application, I created a function called
>> GetValidatedTempDir() which does the get and validate, so my
>> suggestions/comments would be as follows:
>> - both flavours should verify the path exists.
>> - a more 'temp-path' centric error might be good. I must confess to
>> not knowing a great feal about the error codes. I usually have an
>> outer catch for const std::exception& and expect that calling what()
>> on that would give me something meaningful. If the temporary directory
>> getter threw an exception if validation fails, and if calling what()
>> on that gave me some idea about a problem with the temp path, then I'd
>> be happy.
>> - I don't think the path should be created.
> Ok, the following uses filesystem's error facility to optionally throw
> or set errcode. It verfies the path is a directory, which IIUC, implies
> path existence.

Here's a version that actually compiles, at least on windows:

   path temp_dir_path(system::error_code* ec)
       const char* val = std::getenv("TMPDIR");

       if (error(val==0,
         ec, "boost::filesystem::temp_dir_path"))
           return path();

       path p(val);

       if (error((ec && !is_directory(p, *ec)) ||
         (!ec && !is_directory(p)),
         ec, "boost::filesystem::temp_dir_path"))
           return path();

       return p;

# else // Windows

       std::vector<path::value_type> buf(GetTempPathW(0, NULL));

       if (error(GetTempPathW(buf.size(), &buf[0])==0,
         ec, "boost::filesystem::temp_dir_path"))
           return path();

       path p(buf.begin(), buf.end());

       if (error((ec && !is_directory(p, *ec)) ||
           (!ec && !is_directory(p)),
         ec, "boost::filesystem::temp_dir_path"))
           return path();

       return p;
# endif


Boost list run by bdawes at, gregod at, cpdaniel at, john at