Exemplo n.º 1
0
Scanner::Scanner(const std::string& filename, int type, bool md5 /* = false */)
    : m_filename(filename), m_stream(nullptr), m_source(nullptr), m_len(0), m_pos(0),
      m_state(Start), m_type(type), m_yyscanner(nullptr), m_token(nullptr),
      m_loc(nullptr), m_lastToken(-1), m_isHHFile(0), m_lookaheadLtDepth(0),
      m_listener(nullptr) {
#ifdef _MSC_VER
  // I really don't know why this doesn't work properly with MSVC,
  // but I know this fixes the problem, so use it instead.
  std::ifstream ifs =
    std::ifstream(m_filename, std::ifstream::in | std::ifstream::binary);
  if (ifs.fail()) {
    throw FileOpenException(m_filename);
  }

  std::stringstream ss;
  ss << ifs.rdbuf();
  m_stream = new std::istringstream(ss.str());
  m_streamOwner = true;
#else
  m_stream = new std::ifstream(m_filename);
  m_streamOwner = true;
  if (m_stream->fail()) {
    delete m_stream; m_stream = nullptr;
    throw FileOpenException(m_filename);
  }
#endif
  if (md5) computeMd5();
  init();
}
Exemplo n.º 2
0
// Loads table content from a file
void Table::load(std::string fname)
{
    const std::vector<char> delims = {delim};
    std::ifstream in(fname);
    if (in.fail()) throw FileOpenException();

    // Delete old table
    data.clear();

    int k = 0;

    while (!in.eof())
    {
        k++;
        std::string line;
        // Load a line
        getline(in, line);
        // Split a line by cell delimiter
        std::vector<std::string> parsed = split_string(line, delims, false, true);
        int l = 0;
        for (auto it = parsed.begin(); it < parsed.end(); it++)
        {
            l++;
            // Remove spaces
            trim(*it, ' ');
            // Dont put empty cells
            if (*it == "") continue;
            set_cell(CellReference(k, l), *it);
        }
    }
}
Exemplo n.º 3
0
// Saves table content to a file
// if original_text is true, saves original content, not evaluated numbers / errors
void Table::save(std::string fname, bool original_text)
{
    std::ofstream out(fname);
    if (out.fail()) throw FileOpenException();
    int k = 1;
    for (auto ita = data.begin(); ita != data.end(); ita++)
    {
        // Printing empty lines (for empty lines of the table)
        while (k < ita->first)
        {
            out << std::endl;
            k++;
        }
        int l = 1;
        for (auto itb = (ita->second).begin(); itb != (ita->second).end(); itb++)
        {
            // Printing delimiters for empty cells
            while (l < itb->first)
            {
                out << delim;
                l++;
            }
            // Printing the cell itself
            if (original_text)
            {
                out << (itb->second).get_text();
            }
            else
            {
                out << (itb->second).get_content();
            }
        }
    }

}
Exemplo n.º 4
0
void FileReaderTXT::getRaw(char *p, streamsize size)
{
	inputFile->read(p, size);
	if (inputFile->gcount() != size) {
		throw FileOpenException("error during reading", fileName.fullPath());
	}
}
Exemplo n.º 5
0
void FileWriterBF::openFile(bool append)
{
	bf = new bffilebuf(fileName, append ? ios::out | ios::app : ios::out);
	if (!bf || !bf->is_open()) {
		Logger::warning << "could not write to file '" << fileName.fullPath() << "'" << endl;
		throw FileOpenException("Could not open file for writing.", fileName.fullPath());
	}
	outputFile = new ostream(bf);
}
Exemplo n.º 6
0
void Config::loadFile(const std::string& fileName) throw(FileOpenException,DataParsingException)
{
// code mostly basis on TinyXML example
    TiXmlDocument doc(fileName.c_str());
    if (!doc.LoadFile())
        throw FileOpenException(fileName);

    TiXmlHandle hDoc(&doc);
    TiXmlElement* pElem;
    TiXmlHandle hRoot(0);

    std::string m_name; // check what for it is

	// block: name
	{
		pElem=hDoc.FirstChildElement().Element();
		// should always have a valid root. If does not - throw exception.
		if (!pElem)
            throw XML::XMLParsingException(fileName);

		m_name=pElem->Value();

		// save this for later
		hRoot=TiXmlHandle(pElem);
	}

    // <configuration>
	{
		config.clear(); // trash existing table

		pElem=hRoot.FirstChild().Element();
		for(; pElem; pElem=pElem->NextSiblingElement())
		{
			std::string pKey = pElem->Value();
			std::string pText = pElem->GetText();
            std::string pAttr = pElem->Attribute("name");
            SupportedTypesVariant value;
            try
            {
                value = fromStringToTypeVariableMap[pKey](pText);
            }
            catch(boost::bad_lexical_cast&)
            {
                throw XML::WrongTypeOfValueException(pKey,pText);
            }
			if (pKey.length() > 0 && pText.length() > 0)
			{
			    config[pAttr] = value;
			}
        }
	}

}
Exemplo n.º 7
0
FileInputStream::FileInputStream(const std::string& path)
{
#ifdef _WIN32
	if (fopen_s(&_fp, path.c_str(), "rb") != 0)
		throw FileOpenException();
#else
	_fp = std::fopen(path.c_str(), "rb");
	if (!_fp)
		throw FileOpenException();
#endif

	std::fseek(_fp, 0L, SEEK_END);
	
	long temp = std::ftell(_fp);
	if (temp == -1L)
		throw FileOpenException();

	_fileSize = std::size_t(temp);

	std::fseek(_fp, 0L, SEEK_SET);
}
Exemplo n.º 8
0
Scanner::Scanner(const char *filename, int type, bool md5 /* = false */)
    : m_filename(filename), m_stream(nullptr), m_source(nullptr), m_len(0), m_pos(0),
      m_state(Start), m_type(type), m_yyscanner(nullptr), m_token(nullptr),
      m_loc(nullptr), m_lastToken(-1), m_isStrictMode(0), m_lookaheadLtDepth(0) {
  m_stream = new std::ifstream(filename);
  m_streamOwner = true;
  if (m_stream->fail()) {
    delete m_stream; m_stream = nullptr;
    throw FileOpenException(filename);
  }
  if (md5) computeMd5();
  init();
}
Exemplo n.º 9
0
void Util::hash_file(std::string file_path) {
    std::ifstream fin(file_path, std::ifstream::binary);
    char buffer[FILE_STEP];

    if (!fin.is_open()) {
        throw FileOpenException();
    }

    while (!fin.eof()) {
        fin.read(buffer, FILE_STEP);
        hash_chunk(buffer, fin.gcount());
    }

    fin.close();
}
Exemplo n.º 10
0
Scanner::Scanner(const char *filename, int type)
    : m_filename(filename), m_source(NULL), m_len(0), m_pos(0),
      m_state(Start), m_type(type), m_yyscanner(NULL), m_token(NULL),
      m_loc(NULL), m_lastToken(-1), m_gap(false), m_inScript(false),
      m_xhpState(0) {
  m_stream = new ifstream(filename);
  m_streamOwner = true;
  if (m_stream->bad()) {
    delete m_stream; m_stream = NULL;
    throw FileOpenException(filename);
  }
  if (type & PreprocessXHP) {
    istream *is = preprocessXHP(*m_stream, m_sstream, filename);
    if (m_stream != is) {
      delete m_stream;
      m_stream = is;
      m_streamOwner = false;
    }
  }
  init();
}
Exemplo n.º 11
0
bool FileReaderTXT::openFile(bool throwError)
{
	inputFile = FileUtils::newIfstream(fileName.fullPath());

	if (inputFile == 0) {
		if (throwError) {
			Logger::warning << "could not read from file '" << fileName.fullPath() << "'" << " (" << strerror(errno) << ")" << endl;
			throw FileOpenException("could not open file for reading", fileName.fullPath());
		} else {
			Logger::debug << "file not found: '" << fileName.fullPath() << "'" << " (" << strerror(errno) << ")" << endl;
			return false;
		}
	}

	lineNumber = 0;

	// read first line
	nextLine();

	return true;
}
Exemplo n.º 12
0
File::File( const std::string & fileName, Mode mode, Type type )
{
    m_fileName = fileName;
#ifdef USE_CSTD_FILE
    char modeStr[3] = "\0\0";
    modeStr[0] = (mode == File::ReadMode  ?  'r'  :  'w');
    if ( type == File::Binary )
        modeStr[1] = 'b';
    m_file = fopen( fileName.c_str(), modeStr );

    const char * modeNames[] = { "Reading", "Writing" };
    if ( m_file != 0 )
    {
        ms_log( Logger::Info, "Opened %s for %s",
                m_fileName.c_str(), modeNames[ mode ] );
    }
    else
    {
        ms_log( Logger::Error, "Unable to open %s for %s",
                m_fileName.c_str(), modeNames[ mode ] );
        throw FileOpenException( m_fileName, mode );
    }
#endif
}
 FFData(const std::string &path, VSFileSystem::VSFileType type, Format &fmt, int streamIdx) throw(Exception) :
     pFormatCtx(0),
     pCodecCtx(0),
     pCodec(0),
     pStream(0),
     packetBuffer(0),
     packetBufferSize(0),
     sampleBufferBase(0),
     filepath(path),
     filetype(type),
     audioStreamIndex(streamIdx)
 {
     packet.data = 0;
     
     char buf[(sizeof(type)+1)/2+1];
     sprintf(buf, "%d", type);
     
     // Initialize libavcodec/libavformat if necessary
     FFMpeg::initLibraries();
     
     // Open file
     std::string npath = std::string("vsfile:") + path + "|" + buf;
     std::string errbase = std::string("Cannot open URL \"") + npath + "\"";
     
     if (  (0 != av_open_input_file(&pFormatCtx, npath.c_str(), NULL, BUFFER_SIZE, NULL))
         ||(0 >  av_find_stream_info(pFormatCtx))  )
         throw FileOpenException(errbase + " (wrong format or file not found)"); 
     
     // Dump format info in case we want to know...
     #ifdef VS_DEBUG
     dump_format(pFormatCtx, 0, npath.c_str(), false);
     #endif
     
     // Find audio stream
     pCodecCtx = 0;
     streamIndex = -1;
     for (unsigned int i=0; (pCodecCtx==0) && (i < pFormatCtx->nb_streams); ++i)
         if ((pFormatCtx->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO) && (streamIdx-- == 0))
             pCodecCtx = (pStream = pFormatCtx->streams[streamIndex = i])->codec;
     if (pCodecCtx == 0)
         throw FileOpenException(errbase + " (wrong or no audio stream)");
     
     // Find codec for the audio stream and open it
     pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
     if(pCodec == 0)
         throw CodecNotFoundException(errbase + " (unsupported codec)");
     
     if(avcodec_open(pCodecCtx, pCodec) < 0)
         throw CodecNotFoundException(errbase + " (unsupported codec)");
     
     // Get some info
     fmt.sampleFrequency = pCodecCtx->sample_rate;
     fmt.channels = pCodecCtx->channels;
     fmt.nativeOrder = 1; // always so for ffmpeg
     switch (pCodecCtx->sample_fmt) {
     case SAMPLE_FMT_U8:  fmt.bitsPerSample = 8;
                          fmt.signedSamples = 0;
                          break;
     case SAMPLE_FMT_S16: fmt.bitsPerSample = 16;
                          fmt.signedSamples = 1;
                          break;
     #ifdef SAMPLE_FMT_S24
     case SAMPLE_FMT_S24: fmt.bitsPerSample = 24;
                          fmt.signedSamples = 1;
                          break;
     #endif
     #ifdef SAMPLE_FMT_S32
     case SAMPLE_FMT_S32: fmt.bitsPerSample = 32;
                          fmt.signedSamples = 1;
                          break;
     #endif
     default:             throw CodecNotFoundException(errbase + " (unsupported audio format)");
     }
     sampleSize = (fmt.bitsPerSample + 7) / 8 * fmt.channels;
     assert(sampleSize > 0);
     
     // Initialize timebase counter
     sampleBufferStart = 0;
     streamSize = 0;
 
     // Initialize sample buffer
     sampleBufferBase = malloc(sampleSize * BUFFER_SIZE + BUFFER_ALIGNMENT);
     ptrdiff_t offs = ((reinterpret_cast<ptrdiff_t>(sampleBufferBase)) & (BUFFER_ALIGNMENT-1));
     sampleBufferAligned = ((char*)sampleBufferBase) + BUFFER_ALIGNMENT - offs;
     sampleBufferAlloc = sampleSize * BUFFER_SIZE;
     sampleBuffer = 0;
     sampleBufferSize = 0;
 }