libmoost
/home/mhx/git/github/libmoost/include/moost/io/file_operations.hpp
Go to the documentation of this file.
00001 /* vim:set ts=3 sw=3 sts=3 et: */
00028 #ifndef MOOST_IO_FILE_OPERATIONS_HPP__
00029 #define MOOST_IO_FILE_OPERATIONS_HPP__
00030 
00031 #include <errno.h>
00032 #include <stdexcept>
00033 #include <string>
00034 #include <cstring>
00035 #include <boost/cstdint.hpp>
00036 
00037 #if defined(__GNUC__)
00038 #include <unistd.h>
00039 #elif defined(_MSC_VER)
00040 #include <io.h>
00041 #include <fcntl.h>
00042 #include <sys/types.h>
00043 #include <sys/stat.h>
00044 #include <stdio.h>
00045 #include <share.h>
00046 #endif
00047 
00052 namespace moost { namespace io {
00053 
00057 class file_operations
00058 {
00059 private:
00060 
00064   static std::string get_error_string(int err)
00065   {
00066     char buf[512];
00067 #if defined(__GNUC__)
00068     strerror_r(err, buf, sizeof(buf));
00069 #elif defined(_MSC_VER)
00070     strerror_s(buf, sizeof(buf), err);
00071 #endif
00072     return std::string(buf);
00073   }
00074 
00075 public:
00076 
00081   static void change_size(const std::string & path, boost::int64_t length)
00082   {
00083 #if defined(__GNUC__)
00084     if (truncate(path.c_str(), length) != 0)
00085       throw std::runtime_error("could not change size: " + get_error_string(errno));
00086 #elif defined(_MSC_VER)
00087     int fh;
00088 
00089     if( _sopen_s( &fh, path.c_str(), _O_RDWR, _SH_DENYNO, _S_IREAD | _S_IWRITE ) == 0 )
00090     {
00091       int result = _chsize_s( fh, length );
00092       if (result != 0)
00093       {
00094         _close( fh );
00095         throw std::runtime_error( std::string("could not change size: ") + get_error_string(errno) );
00096       }
00097       _close( fh );
00098     }
00099     else
00100       throw std::runtime_error("could not open file: " + get_error_string(errno));
00101 #endif
00102   }
00103 };
00104 
00105 }} // moost::io
00106 
00107 #endif // MOOST_IO_FILE_OPERATIONS_HPP__