MXS-1461 Add TempFile

Class for creating a temporary file.
This commit is contained in:
Johan Wikman
2017-11-15 14:34:22 +02:00
parent edb271fa8e
commit da989d636e
2 changed files with 120 additions and 0 deletions

View File

@ -0,0 +1,51 @@
/*
* Copyright (c) 2016 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2020-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
#include "tempfile.hh"
#include <string.h>
#include <unistd.h>
#include <maxscale/debug.h>
namespace
{
static char NAME_TEMPLATE[] = "/tmp/XXXXXX";
}
TempFile::TempFile()
: m_fd(-1)
, m_name(NAME_TEMPLATE)
{
m_fd = mkstemp((char*)m_name.c_str());
ss_dassert(m_fd != -1);
}
TempFile::~TempFile()
{
int rc = unlink(m_name.c_str());
ss_dassert(rc != -1);
close(m_fd);
}
void TempFile::write(const void* pData, size_t count)
{
int rc = ::write(m_fd, pData, count);
ss_dassert(rc != -1);
ss_dassert((size_t)rc == count);
}
void TempFile::write(const char* zData)
{
write(zData, strlen(zData));
}

View File

@ -0,0 +1,69 @@
#pragma once
/*
* Copyright (c) 2016 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2020-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
#include <string>
/**
* TempFile is a class using which a temporary file can be created and
* written to.
*/
class TempFile
{
TempFile(const TempFile&);
TempFile& operator = (const TempFile&);
public:
/**
* Constructor
*
* Create temporary file in /tmp
*/
TempFile();
/**
* Destructor
*
* Close and unlink file.
*/
~TempFile();
/**
* The name of the created temporary file.
*
* @return The name of the file.
*/
std::string name() const
{
return m_name;
}
/**
* Write data to the file.
*
* @param pData Pointer to data.
* @param count The number of bytes to write.
*/
void write(const void* pData, size_t count);
/**
* Write data to the file.
*
* @param zData Null terminated buffer to write.
*/
void write(const char* zData);
private:
int m_fd;
std::string m_name;
};