forked from ravinet/mahimahi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemp_file.cc
63 lines (51 loc) · 1.44 KB
/
temp_file.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* -*-mode:c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <cassert>
#include "temp_file.hh"
#include "exception.hh"
#include "util.hh"
using namespace std;
vector<char> to_mutable( const string & str )
{
vector< char > ret;
for ( const auto & ch : str ) {
ret.push_back( ch );
}
ret.push_back( 0 ); /* null terminate */
return ret;
}
UniqueFile::UniqueFile( const string & filename_template )
: mutable_temp_filename_( to_mutable( filename_template + ".XXXXXX" ) ),
fd_( SystemCall( "mkstemp", mkstemp( &mutable_temp_filename_[ 0 ] ) ) ),
moved_away_( false )
{
}
/* unlike UniqueFile, a TempFile is deleted when object destroyed */
TempFile::~TempFile()
{
if ( moved_away_ ) { return; }
try {
SystemCall( "unlink " + name(), unlink( name().c_str() ) );
} catch ( const Exception & e ) {
e.perror();
}
}
void UniqueFile::write( const string & contents )
{
assert( not moved_away_ );
fd_.write( contents );
}
UniqueFile::UniqueFile( UniqueFile && other )
: mutable_temp_filename_( other.mutable_temp_filename_ ),
fd_( move( other.fd_ ) ),
moved_away_( false )
{
other.moved_away_ = true;
}
string UniqueFile::name( void ) const
{
assert( mutable_temp_filename_.size() > 1 );
return string( mutable_temp_filename_.begin(), mutable_temp_filename_.end() - 1 );
}