예제 #1
0
void 		Bomberman::loadGame() {
	GameScene *ptr;
  	char  *cfile;
  	std::string tmp;

  	cfile = BUtils::openFileDialog("Please choose your saved game");
  	if (cfile) {
  		tmp = cfile;
  		std::ifstream filestream(cfile, std::ifstream::in);
  		if (filestream && BUtils::checkMd5(tmp)) {
			if (this->_scenes[GAME])
				delete this->_scenes[GAME];
			ptr = new GameScene(this, this->_keyController, this->_camera);
			ptr->loadGame(tmp);
			this->_scenes[GAME] = ptr;
			this->_scenes[GAME]->initialize();
			this->setScene(GAME);

  		} else {
  			BUtils::runDialog(GTK_MESSAGE_ERROR, "The map file cannot be opened or is invalid.");
  		}
  	} else {
  		BUtils::runDialog(GTK_MESSAGE_WARNING, "You haven't chosen a file.");
  	}
}
예제 #2
0
std::string GetShaderFileText(const std::string& filepath)
{
    std::ifstream filestream(filepath, std::ios::in);
    if(!filestream) {
        return std::string();
    }
    
    filestream.seekg(0, filestream.end);
    int sz = (int) filestream.tellg();
    filestream.seekg(0, filestream.beg);
    
    if(sz > 0)
    {
        char buf [sz];
        memset(buf, 0, sz+1);
        
        filestream.read(buf, sz);
        filestream.close();
        
        return std::string(buf, sz);
    }
    
    filestream.close();
    return std::string();
}
예제 #3
0
파일: graph2.cpp 프로젝트: fdimeo/graph2
Graph::Graph(char *fileName)
{

   m_totalNumVerticies = 0;
   m_totalNumEdges = 0;

   int graphSize;
   
   // read the graph from a file.
   // the first int is the size, and followed by tuples of int node1, int node2, int cost
   // open the graph file for read only
   std::fstream filestream(fileName, std::fstream::in );

   filestream >> graphSize;

   std::cout << " graph size is " << graphSize << " nodes" << std::endl;

   while(true)
   {    
      unsigned int node1, node2, cost;
      
      // collect a edge data
      filestream >> node1 >> node2 >> cost;

      // only read with the input is valid
      if(filestream.eof()) break;

      std::cout << "node1: " << node1 << " node2: " << node2 << " cost: " << cost << std::endl;
      addNode(node1);       // these addNode calls are idempotent 
      addNode(node2);
      addEdge(node1, node2 , cost);
   }
}
예제 #4
0
static const std::vector<uint8_t>* GetFileData(const std::string& abspath,
                                               YFileUtils::FileEnv* file_env) {
  auto map_iter = mFileCache.find(abspath);
  if (map_iter != mFileCache.end()) {
    return &(*map_iter).second;
  }

  // Read file into inserted vector.
  YFileUtils::FileStream filestream(abspath,
                                    YFileUtils::FileStream::kFileMode_Read,
                                    YFileUtils::FileStream::kFileType_Binary,
                                    file_env);
  if (!filestream.IsOpen()) {
    std::cerr << "Could not open file: " << abspath << std::endl;
    return NULL;
  }

  std::vector<uint8_t>& file_data = mFileCache[abspath];
  if (!filestream.Read(file_data)) {
    std::cerr << "Error reading file: " << abspath << std::endl;
    return NULL;
  }

  return &file_data;
}
예제 #5
0
void testRedirect()
{
    std::ofstream filestream("redirect_cout");
    std::cout << "Before redirect." << std::endl;
    {
        ScopedRedirect redirect(std::cout, filestream);
        std::cout << "During redirect." << std::endl;
    }
    std::cout << "After redirect." << std::endl;
}
예제 #6
0
void outputResult::writeResult(int iCount,tlCF::GameResult result)
{
	std::fstream filestream(_fileName, std::ios::app);
	filestream << iCount << " ; " << (int)result.result << " ; ";
	for (int iCount = 0; iCount < 42; iCount++)
	{
		filestream << (int)result.moves[iCount] << " ; ";
	}
	filestream << std::endl;
	filestream.close();
}
예제 #7
0
int Waypointlijst::save()
{	std::ofstream filestream("Waypoint_file");
    map<string, GPSpositie>::iterator itr;
    itr=waypoints.begin();
    do
    {	filestream <<itr->first<<', '<<itr->second.getNB()<<', '<<itr->second.getOL()<<endl;
        itr++;
    }
    while (itr != waypoints.end());
    filestream.close();
    return 1;
}
예제 #8
0
int RL_MultiTable::_lines(const char * const filename)
{
	ifstream filestream(filename);

	int c = 0;
	string line;

	//count the lines
	while( getline(filestream, line) )
		c++;

	return c;
}
예제 #9
0
static void fill_container_with_file(QList<QColor> &container, const QString &filename)
{
    QFile file(filename);

    file.open(QIODevice::ReadOnly | QIODevice::Text);

    QTextStream filestream(&file);

    /* discarding all the uninteresting lines, should find a more effective way */
    while (!filestream.atEnd() && filestream.status() != QTextStream::ReadCorruptData)
    {
	container << filestream.readLine();
    }
}
예제 #10
0
bool ModSystem::startPlayback(std::string filename) {
    std::ifstream filestream(filename, std::fstream::binary);
    
    if (!filestream.is_open()) {
        return false;
    }

    m_currentPlaybackData.clear();

    m_currentPlaybackData =
        std::vector<char>(std::istreambuf_iterator<char>(filestream),
                          std::istreambuf_iterator<char>());

    return startPlayback(m_currentPlaybackData.data());
}
예제 #11
0
static QString get_line(const QString & filename, int linenum)
{
    QFile file(filename);

    file.open(QIODevice::ReadOnly | QIODevice::Text);

    QTextStream filestream(&file);

    /* discarding all the uninteresting lines, should find a more effective way */
    for (int i = 0; i < linenum; i++)
    {
        filestream.readLine();
    }

    return filestream.readLine();
}
예제 #12
0
static void fill_container_with_file(T &container, const QString & filename)
{
    QFile file(filename);

    file.open(QIODevice::ReadOnly | QIODevice::Text);

    QTextStream filestream(&file);

    /* discarding all the uninteresting lines, should find a more effective way */
    while (!filestream.atEnd() && filestream.status() != QTextStream::ReadCorruptData)
    {
	typename T::value_type var;
	filestream >> var;
	container << var;
    }
}
예제 #13
0
  void Odometer::loadConfig(std::string filename)
  {
    // Describe the valid options
    po::options_description desc;
    desc.add_options()
      ("odometer.meters_per_tick", po::value<double>());

    // Create a place to store the option values
    po::variables_map vm;
    // Load the options into the map
    std::ifstream filestream(filename.c_str());
    po::store(po::parse_config_file(filestream, desc, true), vm);
    po::notify(vm);

    // Assign the values to the appropriate places
    this->meters_per_tick = vm["odometer.meters_per_tick"].as<double>();
  }
예제 #14
0
Properties::Properties(const char* propFileName) {
	// Load file
	string row;
	fstream filestream(propFileName, fstream::in);
	if (!filestream.is_open()) {
		string errorString("File not found, ");
		throw runtime_error(errorString+propFileName);
	}
	while (getline(filestream, row)) {
		int i = row.find('=');
		if(i > 0) {
			propMap[row.substr(0,i)]=row.substr(i+1);
		}
		//cout << a++ << ":" << row.substr(0, i) << " = " << row.substr(i + 1) << endl;
	}
	filestream.close();
}
예제 #15
0
	void FontRenderer::LoadCharInfos(std::wstring &font)
	{
		std::ifstream filestream(font + L".fnt");

		char buffer[128];
		filestream.getline(buffer,128);

		unsigned int scale_w,scale_h,line_height,base;
		sscanf_s(buffer,"common lineHeight=%d base=%d scaleW=%d scaleH=%d",&line_height,&base,&scale_w,&scale_h);

		memset(char_infos,0,256*sizeof(CharacterInfo*));

		while(!filestream.eof()) {
			CharacterInfo char_info;

			unsigned int id;
			int x,y;
			int width,height;
			int xoffset,yoffset;
			int xadvance;

			filestream.getline(buffer,128);
			int test = sscanf_s(buffer,"char id=%d x=%d y=%d width=%d height=%d xoffset=%d yoffset=%d xadvance=%d",
				&id,&x,&y,&width,&height,&xoffset,&yoffset,&xadvance);

			if(id>255 || test!=8) continue;

			char_info.x = (float)x/(float)scale_w;
			char_info.y = (float)y/(float)scale_h;
			char_info.width = (float)width;
			char_info.height = (float)height;
			char_info.tex_width = (float)width/(float)scale_w;
			char_info.tex_height = (float)height/(float)scale_h;
			char_info.xoffset = (float)xoffset;
			char_info.yoffset = (float)yoffset;
			char_info.xadvance = (float)xadvance;			

			if(!char_infos[id]) {
				char_infos[id] = new CharacterInfo;
				*char_infos[id] = char_info;
			}
		}

		filestream.close();
	}
예제 #16
0
파일: fileutil.cpp 프로젝트: gkathire/wxVCL
bool FileIsText(wxString const & AFilename, bool & /* OUT-only */ FileReadable)
{
	wxUnusedVar(FileReadable);
	wxFileInputStream filestream(AFilename);
	if (filestream.IsOk() == false)
		return false;

	bool hit = false;
	do
	{
		wxChar a;
		filestream.Read(&a, 1);
		if (((int)a < 7) || (((int)a >= 14) && ((int)a <= 31)))
			hit = true;
	}
	while ((filestream.Eof() == false) || hit);
	return !hit;
}
void RandomMaskGenerator::PrintDataToFile(const char* filename)
{
    assert(p_data != nullptr);

    std::ofstream filestream(filename, std::ios_base::out | std::ios_base::binary);

    filestream.write(reinterpret_cast<const char*>(&kSCREEN_WIDTH), sizeof(&kSCREEN_WIDTH));
    filestream.write(reinterpret_cast<const char*>(&kSCREEN_HEIGHT), sizeof(&kSCREEN_HEIGHT));
    filestream.write(reinterpret_cast<const char*>(&m_maskSize), sizeof(&m_maskSize));
    filestream.write(reinterpret_cast<const char*>(&kNUMRANDOMMASKS), sizeof(kNUMRANDOMMASKS));

    for(unsigned int i = 0; i < kNUMRANDOMMASKS; ++i)
    {
        filestream.write(reinterpret_cast<const char*>(&p_data[i * m_maskSize]),
                         m_maskSize * sizeof(int));
    }

    filestream.close();
}
예제 #18
0
파일: utility.cpp 프로젝트: Cydrak/dasShiny
string Utility::importMedia(string pathname) {
  string container;
  
  if(file::exists(pathname) && file::size(pathname) <= 0x10000) {
    // Check if it's one of the system ROMs
    if(auto manifest = program->getUserResource("Nintendo DS.sys/manifest.bml")) {
      auto elem     = Markup::Document(vectorstream(manifest()).text());
      auto contents = file::read(pathname);
      auto hash     = sha256(contents.data(), contents.size());
      auto sysfolder = program->savePath("Nintendo DS.sys/");
      
      if(hash == elem["system/memory/arm9/sha256"].text()) {
        string dest = {sysfolder, elem["system/memory/arm9/data"].text()};
        file::write(dest, contents);
        return "<system>";
      }
      else if(hash == elem["system/memory/arm7/sha256"].text()) {
        string dest = {sysfolder, elem["system/memory/arm7/data"].text()};
        file::write(dest, contents);
        return "<system>";
      }
    }
  }
  
  if(!NintendoDS::validateHeader(filestream(pathname, file::mode::read))) {
    MessageWindow().setTitle("Import failed").setText(
      {"Couldn't import ",pathname,".\n"
       "\n"
       "This file doesn't look like a Nintendo DS title.\n"})
      .error();
    return "";
  }
  else if(!NintendoDS::importROMImage(container, libraryPath(), pathname)) {
    MessageWindow().setTitle("Import failed").setText(
      {"Couldn't import ",pathname,".\n"
       "\n"
       "Check to see if you've got sufficient permissions and disk space."})
      .error();
    return "";
  }
  return container;
}
예제 #19
0
static void fill_uid_str(QHash<Pokemon::uniqueId, QString> &container, const QString &filename, bool trans = false)
{
    container.clear();

    foreach(QString fileName, PokemonInfoConfig::allFiles(filename, trans)) {
        QFile file(fileName);
        file.open(QIODevice::ReadOnly | QIODevice::Text);
        QTextStream filestream(&file);
        /* discarding all the uninteresting lines, should find a more effective way */
        while (!filestream.atEnd() && filestream.status() != QTextStream::ReadCorruptData)
        {
            QString current = filestream.readLine().trimmed();
            QString other_data;
            Pokemon::uniqueId pokeid;
            bool ok = Pokemon::uniqueId::extract(current, pokeid, other_data);
            if(ok) {
                container[pokeid] = other_data;
            }
        }
    }
예제 #20
0
Chain * get_chain_from_perl_gen_pdb_file(string & filename) {
    ifstream filestream(filename.c_str());
    ASSERT(filestream.is_open(), "Could not open input PDB file " + STRING(filename));

    Chain * chain = NULL;
    Residue * current_residue = NULL;
    Atom * current_atom = NULL;

    string line, line_key, atom_name, resname, chain_id, element;
    int atom_id, residue_id;
    double * coords = new double [3];

    while (getline(filestream, line)) {
        element = line[13];
        istringstream iss(line);
        iss >> line_key; // get ATOM
        iss >> atom_id; // get atom id
        iss >> atom_name; // get atom name (ex CA)
        iss >> resname; // get residue name (ex HIS)
        iss >> chain_id; // get chain id
        iss >> residue_id; // get residue id
        iss >> coords[0];
        iss >> coords[1];
        iss >> coords[2];

        if (chain == NULL)
            chain = new Chain(chain_id);

        if (current_residue == NULL or current_residue->id != residue_id) {
            current_residue = new Residue(residue_id, resname);
            chain->add_residue(current_residue);
        }

        current_atom = new Atom(atom_id, atom_name, coords, element);
        current_residue->add_atom(current_atom);
    }
    delete coords;
    return chain;
}
예제 #21
0
	Sequence::Sequence( const Project& project, boost::filesystem::path sequence_file_path )
		: m_project( project )
		, m_location( std::move(sequence_file_path) )
	{
		xml_schema::Properties properties;
		properties.schema_location( aosl::AOSL_XML_NAMESPACE_NAME, path::AOSL_XSD_FILE.string() );

		boost::filesystem::ifstream filestream( full_location() );
		try
		{
			auto sequence = aosl::parse_sequence( filestream, 0, properties );
			m_sequence.reset( sequence.release() );
		}
		catch( const ::xsd::cxx::tree::parsing< char >& e )
		{
			UTILCPP_LOG_ERROR << e.what() << "\nDiagnostic : ";
			
			for( const auto& err : e.diagnostics() )
			{
				UTILCPP_LOG_ERROR << "\n " << err;
			}
			
		}
		
		if( m_sequence )
		{
			m_name = m_sequence->name();
			m_id = m_sequence->id();

			m_library.update( m_sequence->library() );
		}
		else
		{
			m_name = "UNREADABLE SEQUENCE";
			m_id = "";
		}

	}
예제 #22
0
bool WavefrontLoader::isLoadable(const std::string &filepath) const
{
    // The Wavefront OBJ file is loadable only if the extension is 'obj' or 'mod'. We also try to load the file, to
    // ensure the file exists. The 'mod' extension file format signifies a binary Wavefront format.
    
    std::string ext = filepath.substr(filepath.find_last_of(".") + 1);
    
    if ( ext == "obj" || ext == "mod" )
    {
        std::ifstream filestream ( filepath );
        
        if ( filestream )
        {
            return true;
        }
        
        else
        {
            return false;
        }
    }
    
    return false;
}
예제 #23
0
void CpioArchive::EnumerateFiles(StreamReader* reader, std::function<void(CpioFile const&)> func)
{
	cpio_header_t			header;				// Current file header

	if(reader == nullptr) throw Win32Exception(ERROR_INVALID_PARAMETER);

	// Process each file embedded in the CPIO archive input stream
	while(reader->Read(&header, sizeof(cpio_header_t)) == sizeof(cpio_header_t)) {

		// CPIO header magic number is "070701" or "070702" if a checksum is present.
		// (I'm not bothering to test the checksum; can't be used to verify the file data)
		if(strncmp(header.c_magic, "07070", 5) != 0) return;
		if((header.c_magic[5] != '1') && (header.c_magic[5] != '2')) return;

		// Read the entry path string
		char_t path[_MAX_PATH];
		if(reader->Read(path, static_cast<size_t>(ConvertHexString(header.c_namesize, 8))) == 0) path[0] = '\0';
		
		// A path of "TRAILER!!!" indicates there are no more entries to process
		if(strcmp(path, "TRAILER!!!") == 0) return;

		// 32-bit alignment for the file data in the archive
		reader->Seek(align::up(reader->Position, 4));

		// Create a FileStream around the current base stream position
		uint32_t datalength = ConvertHexString(header.c_filesize, 8);
		FileStream filestream(reader, datalength);

		// Invoke the caller-supplied function with a new CpioFile object
		func(std::move(CpioFile(header, path, filestream)));

		// In the event the entire file stream was not read, seek beyond it and
		// apply the 32-bit alignment to get to the next entry header
		reader->Seek(align::up(reader->Position + (datalength - filestream.Position), 4));
	}
}
예제 #24
0
	bool Sequence::save()
	{
		if( m_sequence )
		{

			const auto sequence_file_path = full_location();
			const auto sequence_directory = sequence_file_path.parent_path();
			if( ! boost::filesystem::is_directory( sequence_directory ) )
			{
				boost::filesystem::create_directories( sequence_directory );
			}

			xml_schema::NamespaceInfomap namespace_infos;
			namespace_infos["aos"].name = aosl::AOSL_XML_NAMESPACE_NAME;

			boost::filesystem::ofstream filestream( sequence_file_path );
			aosl::serialize_sequence( filestream, *m_sequence, namespace_infos );
		
			return true;

		}
		else
			return false;
	}
예제 #25
0
Gre::MeshHolder WavefrontLoader::iLoadAsciiWavefront(const std::string &name, const std::string &filepath) const
{
    std::ifstream filestream ( filepath );
    
    if ( !filestream )
    {
        GreDebugPretty() << "Can't open filepath '" << filepath << "'." << std::endl;
        return Gre::MeshHolder ( nullptr );
    }
    
    file_t wavefrontfile;
    
    // So , we must parse the whole file as :
    // Every v , vn , vt , vp statements are always assigned at a number.
    // Every o statement sets a new ind_base corresponding to the last v registered.
    // Every f statement creates a new face with indice will be added the ind_base.
    // Every usemtl statement uses a material which name is 'mtllib + / + materialname'
    
    std::string cur ;
    int ind_basev = 0;
    int ind_baset = 0;
    int ind_basen = 0;
    
    while ( std::getline(filestream, cur) )
    {
        std::stringstream line ( cur );
        std::string met;
        
        while ( line >> met )
        {
            if ( met == "#" ) // Comment line.
                break;
            
            if ( met == "mtllib" ) // Material Library.
            {
                line >> met;
                
                GreDebugPretty() << "Trying to load Material's library '" << met << "'..." << std::endl;
                
                Gre::MaterialManager& matmanager = Gre::ResourceManager::Get().getMaterialManager();
                Gre::MaterialVector material = matmanager.load(met);
                
                if ( material.size() == 0 )
                {
                    GreDebugPretty() << "Sorry , no Materials in given library." << std::endl;
                }
                else
                {
                    GreDebugPretty() << "Material library '" << met << "' ready." << std::endl;
                    wavefrontfile.mtlfile = met;
                }
            }
            
            else if ( met == "o" ) // Objects definition
            {
                line >> met ; // Object name.
                GreDebugPretty() << "Defining new sub-object name '" << met << "'." << std::endl;
                
                obj_t newobject;
                newobject.name = met;
                ind_basev = wavefrontfile.vertexs.size() > 0 ? (int) wavefrontfile.vertexs.size() - 1 : 0;
                ind_baset = wavefrontfile.textures.size() > 0 ? (int) wavefrontfile.textures.size() - 1 : 0;
                ind_basen = wavefrontfile.normals.size() > 0 ? (int) wavefrontfile.normals.size() - 1 : 0;
                
                wavefrontfile.objects.push_back(newobject);
            }
int DataFile_to_Root(
		     std::string file_name = "DataFile_160910_180219.txt",
		     std::string calibration_name = "DataFile_160726_133846.txt"
		     )
{
        //File path and names
        std::string file_path = "data_local/";
				std::string file_path_out = "data_calib/";

	std::string file = file_path + file_name;
	std::string calibration = file_path + calibration_name;

	//Checks to make sure that the files exist at the specified paths
	if(!exist_test(file))
	{
		cerr << "ERROR: DataFile: " << file << " not found." << endl;
		return -1;
	}
	if(!exist_test(calibration))
	{
		cerr << "ERROR: Calibration File: " << file << " not found." << endl;
		return -1;
	}

	//Get calibration factor from file assuming 1:1 mA<->mT conversion
//	double calibration_factor = TMath::Abs(get_calibration_quiet(calibration));
	//double calibration_factor = get_calibration_quiet(calibration);
	double calibration_factor = get_calibration_quiet(calibration);
	double calibration_sign = 1;
	if ( calibration_factor < 0 )
		{
			calibration_sign = -1;
			calibration_factor;
		}

	vector<double> time, current, err_current, InternalField, err_InternalField, position;
	vector<double> ExternalField, err_ExternalField;

	//Count the entries on each line. If 5, the file is a B vs z. If 3, B vs I. Anything else is an error
	std::ifstream filestream(file.c_str());
	std::string s;
	getline(filestream,s);
	int w = 0;
//	int l = strlen(s.c_str());

	TString ts(s);
	TString tok;
	Ssiz_t tokfrom = 0;
	while (ts.Tokenize(tok,tokfrom,"\t"))
		w++;

//	for(int i = 0; i < l; i++)
//	{
//		if ((s[i-1] == '	' || s[i-1] == NULL) && (s[i] != '	')) w++;
//		if (s[i] == NULL) break;
//	}

	//Unpack the file into vectors based on its type
	if(w == 5)
	{
		unpack_file(file, position, InternalField, err_InternalField, current, err_current);
	}
	else if (w == 3)
	{
		unpack_file(file, time, current, InternalField);
	}
	else
	{
		cerr << "ERROR: File does not match known types" << endl;
		return -1;
	}

	//Some files have information which is not represented in other files. For these, fill the vectors with a value which indicates they carry no information.
	if(time.size() < 1)
	{
		for(int i = 0; i < position.size(); i++)
		{
			time.push_back(99999);
		}
	}
	else if (position.size() < 1)
	{
		for(int i = 0; i < time.size(); i++)
		{
			position.push_back(99999);
			err_current.push_back(99999);
			err_InternalField.push_back(99999);
		}

	}

	//Create a root file to store the data taken from the files
	std::string file_root = (file_name.erase(file_name.size()-3,3)).append("root");
//	TFile f((file_path+file_root).c_str(),"RECREATE");
	TFile f((file_path_out+file_root).c_str(),"RECREATE");
	TTree *t = new TTree("t","Conversion of .txt DataFile to ROOT tree");
	double InternalField_i, InternalField_err_i;
	double ExternalField_i, ExternalField_err_i;
	double current_i, current_err_i;
	double position_i, time_i;

	TBranch *b_Position = t->Branch("z",&position_i,"Position of Probe/D");
	TBranch *b_Time = t->Branch("time",&time_i,"Time since start of measurement/D");
	TBranch *b_InternalField = t->Branch("Bi",&InternalField_i,"Field measured inside SC/D");
	TBranch *b_InternalField_err = t->Branch("BiErr",&InternalField_err_i,"Error in Field inside SC/D");
	TBranch *b_ExternalField = t->Branch("Bo",&ExternalField_i,"Field calculated outside SC/D");
	TBranch *b_ExternalField_err = t->Branch("BoErr",&ExternalField_err_i,"Error in Field outside SC/D");
	TBranch *b_calibration = t->Branch("Calibration",&calibration_factor,"Calibration Factor A<->mV and mT/D");
	TBranch *b_current = t->Branch("I",&current_i,"Current through shunt/D");
	TBranch *b_current_err = t->Branch("IErr",&current_err_i,"Error in Current through shunt/D");

	//Fill the output file branches with the data from the file
        for(int i = 0; i < InternalField.size(); i++)
        {
		position_i = position[i];
		time_i = time[i];
		InternalField_i = InternalField[i]*calibration_sign;
		InternalField_err_i = err_InternalField[i];
		ExternalField_i = current[i]*calibration_sign*calibration_factor;
		ExternalField_err_i = err_current[i]*calibration_factor;
		current_i = current[i];
		current_err_i = err_current[i];
		t->Fill();
        }

        f.Write();
        f.Close();

	cout << file_root << " successfully created with " << InternalField.size() << " entries." << endl;

	return 0;
}
예제 #27
0
bool CommandGet::execute(){
	string root = Settings::getInstance().getCwd();
	string filePath = string(root).append(file);

	// GET requested file does not exist.
	if(!fs::exists(filePath) || !fs::is_regular_file(filePath)) {
		sock->writeline("1");
		return true;
	}

	sock->writeline("0");

	int buffSize = 10240;
	long fzCounter = 0;  // counts if we reached the filesize
	ifstream filestream(filePath.c_str(), ios::binary);

	// create stream
	ostringstream stream;
	long filesize = fs::file_size(filePath);

	// Let the client know how large the file is
	char filesizeChar[30];
	sprintf(filesizeChar, "%d", (int)filesize);
	sock->writeline(filesizeChar);

	if(filestream.is_open()) {
		char* defaultBuffer = new char[buffSize];

		filestream.seekg(filestream.beg);

		while(fzCounter != filesize) {

			if((filesize-fzCounter) >= buffSize) {
				// Chunk is large enough, use default buffer
				filestream.read(defaultBuffer, buffSize);
				sock->write(defaultBuffer, buffSize);

				fzCounter += buffSize;
			}else{
				// Chunk is too small, create a tiny buffer
				int remainder = filesize-fzCounter;

				// create small buffer
				char* smallBuff = new char[remainder];

				filestream.read(smallBuff, remainder);
				sock->write(smallBuff, remainder);

				fzCounter += remainder;

				delete [] smallBuff;
			}

		}

		delete [] defaultBuffer;

		filestream.close();
		sock->writeline("0");

		return true;
	}else{
		filestream.close();
		sock->writeline("10");

		return true;
	}

}
예제 #28
0
void interface::on_actionLoad_triggered()
{
    QString filename;
    QString fileopen=QFileDialog::getOpenFileName(this,"load data","","Gea Tuning data (*.gea)");
    if(fileopen.isEmpty()){return;}
    filename=fileopen;

    QFile filestream(filename);

    if(!filestream.open(QFile::ReadOnly|QFile::Text)){
        QMessageBox::critical(this,"Failed","File failed to open");
        return;
    }

    QTextStream fileread(&filestream);
    ui->txtCommData->clear();

    while(!fileread.atEnd()){
        QString received=fileread.readAll();
        ui->txtCommData->insertPlainText(received);
    }

    filestream.flush();
    filestream.close();

    QStringList datalines = ui->txtCommData->toPlainText().split("\n");

    QString tpsline= datalines[0];
    QStringList lsttpsline = tpsline.split(",");
    ui->txtTPSOff->setText(lsttpsline[0]);
    ui->txtTPSFull->setText(lsttpsline[1]);

    QString injecline = datalines[1];
    QStringList lstinjecline = injecline.split(",");
    ui->txtBaseMs->setText(lstinjecline[0]);
    ui->txtOpenMs->setText(lstinjecline[1]);

    int i,j;

    for(i=0;i<cdata;i++){
        QString injline = datalines[2+i];
        QStringList lstinjline = injline.split(",");
        for(j=0;j<cdata;j++){
            QTableWidgetItem* tbl_item = new QTableWidgetItem();
            tbl_item->setText(lstinjline[j]);
            ui->tblInj->setItem(i,j,tbl_item);
        }
    }

    for(i=0;i<cdata;i++){
        QString ignline = datalines[14+i];
        QStringList lstignline = ignline.split(",");
        for(j=0;j<cdata;j++){
            QTableWidgetItem* tbl_item = new QTableWidgetItem();
            tbl_item->setText(lstignline[j]);
            ui->tblIgn->setItem(i,j,tbl_item);
        }
    }

    ui->txtCommData->clear();
}
예제 #29
0
void interface::on_actionSave_triggered()
{
    QString filename;
    QString filesave=QFileDialog::getSaveFileName(this,"save data","","Gea Tuning data (*.gea)");

    if(filesave.isEmpty()){return;}

    QStringList filenameparse = filesave.split(".");

    if(filenameparse.count()==2){
        filename=filenameparse[0];
    }
    else if(filenameparse.count()==1){
        filename=filesave;
    }

    filename += ".gea";

    QFile filestream(filename);
    if(!filestream.open(QFile::WriteOnly|QFile::Text|QFile::Truncate)){
        QMessageBox::critical(this,"Failed","File failed to save");
        return;
    }

    QTextStream filewrite(&filestream);

    filewrite<<ui->txtTPSOff->text()<<","<<ui->txtTPSFull->text()<<endl;
    filestream.flush();

    filewrite<<ui->txtBaseMs->text()<<","<<ui->txtOpenMs->text()<<endl;
    filestream.flush();

    int i;

    for(i=0;i<cdata;i++){
        filewrite<<ui->tblInj->item(i,0)->text()<<",";
        filewrite<<ui->tblInj->item(i,1)->text()<<",";
        filewrite<<ui->tblInj->item(i,2)->text()<<",";
        filewrite<<ui->tblInj->item(i,3)->text()<<",";
        filewrite<<ui->tblInj->item(i,4)->text()<<",";
        filewrite<<ui->tblInj->item(i,5)->text()<<",";
        filewrite<<ui->tblInj->item(i,6)->text()<<",";
        filewrite<<ui->tblInj->item(i,7)->text()<<",";
        filewrite<<ui->tblInj->item(i,8)->text()<<",";
        filewrite<<ui->tblInj->item(i,9)->text()<<",";
        filewrite<<ui->tblInj->item(i,10)->text()<<",";
        filewrite<<ui->tblInj->item(i,11)->text()<<endl;
        filestream.flush();
    }

    for(i=0;i<cdata;i++){
        filewrite<<ui->tblIgn->item(i,0)->text()<<",";
        filewrite<<ui->tblIgn->item(i,1)->text()<<",";
        filewrite<<ui->tblIgn->item(i,2)->text()<<",";
        filewrite<<ui->tblIgn->item(i,3)->text()<<",";
        filewrite<<ui->tblIgn->item(i,4)->text()<<",";
        filewrite<<ui->tblIgn->item(i,5)->text()<<",";
        filewrite<<ui->tblIgn->item(i,6)->text()<<",";
        filewrite<<ui->tblIgn->item(i,7)->text()<<",";
        filewrite<<ui->tblIgn->item(i,8)->text()<<",";
        filewrite<<ui->tblIgn->item(i,9)->text()<<",";
        filewrite<<ui->tblIgn->item(i,10)->text()<<",";
        filewrite<<ui->tblIgn->item(i,11)->text()<<endl;
        filestream.flush();
    }

    filestream.close();
}
예제 #30
0
bool wxMatrix2D::LoadFile( const wxString &filename, const wxArrayInt *cols )
{
    if (filename.IsNull()) return false;

    // valid separators for data
//  const char comma = 44;  // comma
    const char tab = 9;     // tab
    const char space = 32;  // space
//  const char cr = 13;     // carrage return

    wxFile loadfile;
    loadfile.Open( filename, wxFile::read );

    if (!loadfile.IsOpened()) return false;

    m_file_comments.Clear();
//  m_file_comments_positions.Clear();

    wxFileInputStream filestream( loadfile );
    wxTextInputStream textstream( filestream );

    int sizeof_data = 4000;
    double *data = (double*)malloc(sizeof_data*sizeof(double));
    if (data == (double*)NULL) return false;

    wxString line_str, num_str;

    int i, a, b, pos;
    int num_cols = 0;
    int num_rows = 0;
    int num_points = 0;
    int num_lines = 0;
    double point;

    bool fail = false;


    while ( !filestream.Eof() && !fail )
    {
        ++num_lines;

        line_str = textstream.ReadLine();
        if ( filestream.Eof() ) break;

        line_str.Trim(false);
        line_str.Trim(true);


        if (line_str.Left(1) == wxT("#"))
        {
            m_file_comments.Add( line_str );
            //m_file_comments_positions.Add(num_lines);
        }
        else
        {
            ++num_rows;

            // do this once to figure out how many columns of data there is unless already given
            if ( num_cols < 1 )
            {
                for (i = 0; i < 10000; ++i)
                {
                    line_str.Trim(false);
                    a = line_str.Find(space);
                    b = line_str.Find(tab);

                    if ( (a != -1) && (b != -1) ) pos = wxMin( a, b );
                    else if ( a != -1 ) pos = a;
                    else pos = b;

                    if ( pos != -1 ) num_str = line_str.Left( pos );
                    else num_str = line_str;

                    if ( num_str.ToDouble(&point) )
                    {
                        printf("i%d pts%d cols%d rows%d pos%d pt%lf \n", i, num_points, num_cols, num_rows, pos, point); fflush(stdout);
                        //data[i] = point;
                        ++num_cols;
                        line_str = line_str.Right( line_str.Len() - num_str.Len() );
                        ++num_points;
                    }
                    else
                    {
                        i = 10000;
                        break;
                    }
                }
            }
            else
            {
                if ( num_points > sizeof_data - num_cols*2 )
                {
                    data = (double*)realloc( data, sizeof_data+1000 );
                }
                for (i = 0; i < num_cols; ++i)
                {
                    line_str.Trim(false);
                    a = line_str.Find(space);
                    b = line_str.Find(tab);

                    if ( (a != -1) && (b != -1) ) pos = wxMin( a, b );
                    else if ( a != -1 ) pos = a;
                    else pos = b;

                    if ( pos != -1 ) num_str = line_str.Left( pos );
                    else num_str = line_str;

                    if ( num_str.ToDouble(&point) )
                    {
                        printf("i%d pts%d cols%d rows%d pos%d pt%lf \n", i, num_points, num_cols, num_rows, pos, point); fflush(stdout);
                        //data[numpoints*numcolumns + i] = point;
                        line_str = line_str.Right( line_str.Len() - num_str.Len() );
                        ++num_points;
                    }
                    else
                    {
                        // if not just a blank line then data is wrong
                        if (i != 0)
                        {
                            fail = true;
                            wxMessageBox(wxT("# for comments\n7   4\n33  25\n..."),
                                         wxT("Invalid data file format"), wxOK);
                        }
                        i = num_cols;
                        break;
                    }
                }
            }
        }
    }

    // not static
    data = (double*)realloc( data, (num_points+1)*sizeof(double) );
    Create( num_cols, num_rows, data, false );
    loadfile.Close();
    return true;
}