/* PIP - Platform Independent Primitives File Copyright (C) 2011 Ivan Pelipenko peri4ko@gmail.com This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include "pifile.h" bool PIFile::open(const PIString & path_, PIFlags mode_) { cpath = path_; cmode = mode_; string st = cpath.stdString(); if (cmode[New]) { stream.open(st.c_str(), fstream::in | fstream::out | fstream::trunc | fstream::binary); stream.close(); cmode &= ~New; stream.open(st.c_str(), (fstream::openmode)(int)cmode | fstream::binary); } else stream.open(st.c_str(), (fstream::openmode)(int)cmode | fstream::binary); return isOpened(); } PIString PIFile::readLine() { char * buff = new char[4096]; stream.getline(buff, 4096); return PIString(buff); } llong PIFile::readAll(void * data) { llong cp = pos(), s = size(), i = -1; stream.seekg(0); if (s < 0) { while (!stream.eof()) stream.read(&(((char*)data)[++i]), 1); } else stream.read((char * )data, s); seek(cp); return s; } PIByteArray PIFile::readAll(bool forceRead) { llong cp = pos(), s = size(); char c; PIByteArray a; if (s < 0) { if (!forceRead) return a; while (!stream.eof()) { stream.read(&c, 1); a.push_back(c); } seek(cp); return a; } a.resize(s); s = readAll(a.data()); if (s >= 0) a.resize(s); return a; } llong PIFile::size() { if (!stream.is_open()) return -1; llong s, cp = stream.tellg(); stream.seekg(0, fstream::end); s = stream.tellg(); stream.seekg(cp, fstream::beg); stream.clear(); return s; } void PIFile::resize(llong new_size, char fill_) { llong ds = new_size - size(); if (ds == 0) return; if (ds > 0) { char * buff = new char[ds]; memset(buff, fill_, ds); stream.write(buff, ds); delete buff; return; } cout << "[PIFile] Downsize is not support yet :-(" << endl; } llong PIFile::pos() { if (cmode[Write]) return stream.tellp(); if (cmode[Read]) return stream.tellg(); return -1; } PIFile PIFile::openTemporary(PIFlags mode) { char * rc; rc = tmpnam(0); return PIFile(PIString(rc), mode); }