Example #1
0
void Decryptor::empty() {
    if (outFile.good()) {
        outFile.close();
    }
    if (inFile.good()) {
        inFile.close();
    }
}
Example #2
0
bool JobClass::LoadJobFile(fstream &JobStream)
{
	const vector <string> TheTagWords = InitTagWords();

        string FileLine = "";

        FileLine = ReadNoComments(JobStream);

        while (JobStream.good() && !FoundStartTag(FileLine, TheTagWords[0]))     // Job
        {
                FileLine = ReadNoComments(JobStream);
        }

        FileLine = ReadNoComments(JobStream);
        bool BadObject = false;

        while (JobStream.good() && !FoundEndTag(FileLine, TheTagWords[0]))       // Job
        {
                if (!BadObject)
                {
                        if (FoundStartTag(FileLine, TheTagWords[1]))     // Volume
                        {
                                FileLine = ReadNoComments(JobStream);
                                VolumeClass TempVolume;
                                VolID_t VolumeID = TempVolume.ReadJobInfo(FileLine, JobStream);

				if (!TempVolume.ValidConfig())
				{
					cerr << "Problem in JobClass object... Bad Volume..." << endl;
					BadObject = true;
				}
				else
				{
					AddVolume(VolumeID, TempVolume);
				}
                        }
                        else
                        {
                                cerr << "Unknown tags in JobClass object...   Here is the line: " << FileLine << endl;
                                BadObject = true;
			}
                }

                FileLine = ReadNoComments(JobStream);
        }

        if (JobStream.eof())
        {
                cerr << "Early end reading job file." << endl;
        }

	myIsConfigured = !BadObject;
	
	return(myIsConfigured);
}
Example #3
0
void second_pass(){
    reset();
    myReadFile.open(FILE_NAME,ios::in | ios::out);
      if(myReadFile.good() && !myReadFile.eof()){
         getNextTokens();
         cout << "Memory Map" << endl;
         while (!tokens.empty()) {
           defListRead(true);
           useListRead(true);
           programTextRead(true);
           useList.clear();
         }
      //Warning messages
     
      for(vector<string>::iterator it = symbols.begin() ; it != symbols.end() ; ++it){
        if ((useListSymbols.count(*it) > 0)){
          if (useListSymbols[*it].second == 0){
            cout << "Warning: Module " << symDefModuleNum[*it]<< ": " << *it << " was defined but never used " << endl;
          }
         }
        else{
            cout << "Warning: Module " << symDefModuleNum[*it]<< ": " << *it << " was defined but never used " << endl;
          }
      }

      myReadFile.close();
}
}
Example #4
0
void first_pass(){
  string multipleDefinitions = "Error: This variable is multiple times defined; first value used";
  myReadFile.open(FILE_NAME,ios::in | ios::out);
  if(myReadFile.good() && !myReadFile.eof()){
    getNextTokens();
    while (!tokens.empty()) {
      defListRead(false);
      useListRead(false);
      programTextRead(false);
      useList.clear();
    }

    vector<string>::iterator it;
    cout << "Symbol Table" << endl;
 //   cout << symbols.front() << endl;
  
    for(it=symbols.begin() ; it < symbols.end(); it++) {
      cout << *it << "=" <<symbolTable[*it].first; 
      if (symbolTable[*it].second == 1){
        cout <<" "<<  multipleDefinitions;
      }
      cout << endl; 
    }
    tokens.clear();
    cout << endl;
  }
  myReadFile.close();
}
  //--------------------------------------------------------------------
  //--------------------------------------------------------------------
  //  InterpolationFunction
  //--------------------------------------------------------------------
  //--------------------------------------------------------------------
  void InterpolationFunction::initialize(int npts, fstream &fileId, double coef)
  {  // read data
     npts_ = npts;
     xs_.reset(npts);
     fs_.reset(npts);
     fps_.reset(npts);
     double x,f,fp;
     int i = 0;
     while(fileId.good() && i < npts) {
       fileId >> x >> f >> fp;
       xs_(i)=x;
       fs_(i)=coef*f;
       fps_(i)=coef*fp;
       i++;
     }
     // scale tangents 
     double dx, dx0 = xs_(1)-xs_(0); 
     for (int i = 0; i < npts_ ; i++) {
       if      (i   == 0)     { dx = xs_(1)-xs_(0); }
       else if (i+1 == npts_) { dx = xs_(npts_-1)-xs_(npts_-2); }
       else { dx= 0.5*(xs_(i+1)-xs_(i-1)); }
       if (abs(dx-dx0) > 1.e-8) throw ATC_Error("InterpolationFunction::initialize non-uniform data spacing not handled currently");
       fps_(i) *= dx;
     }
     // options: calculate / adjust tangents for monotonicity

  }
Example #6
0
Boolean PrimesTable::TableBuffer::RetrieveBlock(Ulong Index_, long Offset_, fstream& Fin_)
{
  Ulong BlockNum_ = Index_ / PrimesTable::TABLESIZE;

  Fin_.seekg(0, ios::end);
  Fin_.clear();

  long StartPos_ = BlockNum_ * TABLESIZE * sizeof(long);
  long Fsize_ = Fin_.tellg();
  Fsize_ -= Offset_;

  if (StartPos_ < Fsize_)    
    if (Fin_.seekg(StartPos_ + Offset_).good())
    {
      Fin_.read((char*)_Table, TABLESIZE * sizeof(long));

      size_t i;
      long BufSize_ = TABLESIZE;

      for (i = TABLESIZE - 1; i != size_t(-1); --i)
        if (!_Table[i])
          --BufSize_;
        else
          break;

      if (BufSize_)
      {
        StartPos_ /= sizeof(long);
        SetLimit(StartPos_, BufSize_);
        return Fin_.good();
      }
    }

  return FALSE;
}
ElectronPhononExchangeHertel::ElectronPhononExchangeHertel(fstream &fileId,
                                                           map<string,double> & parameters,
                                                           Material * material) 
  : ElectronPhononExchange(),
    exchangeCoef_(0),
    debeyeTemperature_(1),
    massEnhancement_(0),
    material_(material)
{
  if (!fileId.is_open()) throw ATC_Error("cannot open material file");
  vector<string> line;
  while(fileId.good()) {
    command_line(fileId, line);
    if (line.size() == 0) continue;
    if (line[0] == "end") break;
    else if (line[0] == "debeye_temperature") {
      debeyeTemperature_ = str2dbl(line[1]);
      parameters["debeye_temperature"] = debeyeTemperature_;
    }
    else if (line[0] == "mass_enhancement") {
      massEnhancement_ = str2dbl(line[1]);
      parameters["mass_enhancement"] = massEnhancement_;
    }
    else {
      throw ATC_Error( "unrecognized material function "+line[0]);
    }
  }
  // coupling coefficient, eqn. 15 of Hertel 2002
  double kb = LammpsInterface::instance()->kBoltzmann();
  double hbar = LammpsInterface::instance()->hbar();
  double PI = 3.141592653589793238; 
  exchangeCoef_ = 144.*1.0369*kb/(PI*hbar);
  exchangeCoef_ *= massEnhancement_/pow(debeyeTemperature_,2);
}
Example #8
0
// return nabber of filled objects
int fillFromFile(fstream & fin, employee ** pArr, int nSize)
{
	int id;
	int i = 0;

	while (i < nSize && fin.good() && fin.peek() != EOF)
	{
		fin >> id;
		
		switch(id)
		{
		case abstr_emp::EMPLOYEE:
			pArr[i] = new employee;
			break;
		case abstr_emp::MANAGER:
			pArr[i] = new manager;
			break;
		case abstr_emp::FINK: 
			pArr[i] = new fink;
			break;
		case abstr_emp::HIGHFINK: 
			pArr[i] = new highfink;
			break;
		default:
			throw "Error while reading file";
		}
		fin.get(); // '\n'

		pArr[i]->GetAll(fin);
		i++;
	}

	fin.clear();
	return i;
}
Example #9
0
int  main(int argc, char *argv[ ])
{
    float CPU_time, StartTime;
    string buffer;
    ListNode *p;

    extern int unique;

    //cout << "  Purge Program v1.1" << endl;
    init(argc, argv);
    StartTime = (float) clock( );

    /*if(OverWrite)
    	cout << "  Processing input file ...        " << flush;
    else
    	cout << "  Creating output file ...        " << flush;*/
    while(!fin.eof( ))
    {
        fin >> buffer;
        if(fin.good( ))
        {
            entries++;
            insert(buffer);
        }
        //if(entries % 1000 == 0)
        //	cout << "\b\b\b\b\b\b\b" << setw(7) << entries << flush;
    }
    //cout << "\b\b\b\b\b\b\b" << setw(7) << entries << endl;
    if(OverWrite)
        if(duplicates == 0)
            cout << "  File did not contain duplicates and was not overwritten" << endl;
        else
        {
            fin.close( );
            fout.open(argv[1], ios::out);
            if(!fout)
            {
                cout << "  Can not open [" << argv[1] << "] as the output file" << endl;
                exit(1);
            }
            cout << "  Writing unique entries back to source file ...  " << endl;
            p = head;
            while(p != sentinel)
            {
                fout << p->entry << endl;
                p = p->link;
            }
        }
    cout << "  [" << entries << "] entries in file, [" << duplicates << "] duplicates, [" << unique << "] unique entries" << endl;
    CPU_time = (float) clock( ) - StartTime;
    if(CPU_time < 1000.0)
        cout << "  CPU time: [" << CPU_time << "] milliseconds" << endl;
    else
        cout << "  CPU time: [" << CPU_time/1000.0 << "] seconds" << endl;

    return 0;
}
Example #10
0
void showState(fstream &file)
{
   cout << "File Status:\n";
   cout << "  eof bit: " << file.eof() << endl;
   cout << "  fail bit: " << file.fail() << endl;
   cout << "  bad bit: " << file.bad() << endl;
   cout << "  good bit: " << file.good() << endl;
   file.clear();  // Clear any bad bits
}
Example #11
0
void search(){

  //std::cout << "search start" << endl;

  int stl, n=0;
  
  string str, str2;

  while(ifs.good()){

    int i,j=0;
    getline(ifs, str);

    stl = str.length();

    str2 = str;

    transform(str.begin(), str.end(), str.begin(), ::tolower); //全部 小文字に

    /*int h,rep = 0;
    for(int m=0;m <= stl; m++){
      if(str[m] == 0x27){
	rep = 1;
	h=m;
	break;
      }
    }
    
    if(rep == 1){
      str.replace(h,1,"");
      stl= stl - 1;
      }*/
    
    sort(str.begin(), str.end()); //abc順に

    for(i=0; i<16; i++){
      if(str[j] == table[i]){
	j++;
      }

      /*if(j == stl){
	break;
	}*/
    }

    if((j==stl) && (n < stl)){
      //cout << str2 << endl;
       answer = str2;
       n = stl;
    }
    
  }

}
Example #12
0
void wczytajWezly() {
    plik.open( "plik.txt", ios::in | ios::out );
    if(plik.good()==true) {
        float temp;
        for(int i=0;i<rozmiar;i++) {
            for(int j=0;j<i+2;j++) {
                plik >> temp;
                wezly[i].push_back(temp);
            }
        }
        plik.close();
    }
Example #13
0
int addNewEmployees(fstream & fout, employee ** pArr, int nSize)
{
	int i = 0;
	char choice;

	while (i < nSize && fout.good())
	{
		cout << "Wich character you want to create: \n"
			 << "1: employee	2: manager" << endl
			 << "3: fink		4: highfink" << endl
			 << "q: quit" << endl
			 << ">";
		cin >> choice;
		while (strchr("1234q", choice) == NULL)
		{
			cout << "Please enter 1, 2, 3, 4 or q: ";
			cin >> choice;
		}
		cin.ignore(cin.rdbuf()->in_avail());

		if (choice == 'q')
			break;

		switch(choice)
		{
		case '1': 
			pArr[i] = new employee;
			fout << abstr_emp::EMPLOYEE << endl; // mark obj type in file
			break;
		case '2': 
			pArr[i] = new manager;
			fout << abstr_emp::MANAGER << endl;
			break;
		case '3': 
			pArr[i] = new fink;
			fout << abstr_emp::FINK << endl;
			break;
		case '4': 
			pArr[i] = new highfink;
			fout << abstr_emp::HIGHFINK << endl;
			break;
		}
		
		pArr[i]->SetAll();
		pArr[i]->WriteAll(fout);
		cout << endl;
		i++;
	}
	return i;
}
Example #14
0
/************************************************************************
 *                 Maintainence and Administrative			*
 ************************************************************************/
bool JobClass::WriteJobFile(fstream &JobStream) const
{
	const vector <string> TheTagWords = InitTagWords();
	JobStream << "<" << TheTagWords[0] << ">\n";

        for (VolumeIter_Const AVol = myVolumes.begin(); AVol != myVolumes.end(); AVol++)
        {
        	AVol->second.WriteJobList(AVol->first, JobStream);
        }

        JobStream << "</" << TheTagWords[0] << ">\n";
	JobStream.flush();		// makes sure everything has been written
	return(JobStream.good());
}
Example #15
0
int check_flags(const fstream& fh)
{
  int status = 0;
  //cout << "file is:\n";
  if (fh.good())
      status+=16;
  if (fh.bad())
      status+=2;
  if (fh.fail())
      status+=4;
  if (fh.eof())
      status+=8;
  if (0 == status)
      status = -1;

  return status;
}
void VectorRead4(fstream& saveFile,vector<T>& items){
	unsigned int numberofItems = 0;
	saveFile.read((char *) &numberofItems,4);
	items.clear();
	if(numberofItems){
		items.reserve(numberofItems);
		for(unsigned int i=0;i<numberofItems;i++){
			if(!saveFile.good()){
				cerr << "Error in void VectorRead(fstream& saveFile,vector<T> aVector,int version)" << endl; 
				cerr << "FileStream is not good" << endl;
				exit(1);
			}
			T anItem;
			saveFile.read((char *) &anItem,4);
			items.push_back(anItem);
		}
	}
}
Example #17
0
ElectronHeatCapacityLinear::ElectronHeatCapacityLinear(
  fstream &fileId, map<string,double> & parameters) 
  : ElectronHeatCapacity(),
  electronHeatCapacity_(0)
{
  if (!fileId.is_open()) throw ATC_Error(0,"cannot open material file");
  vector<string> line;
  while(fileId.good()) {
    get_command_line(fileId, line);
    if (line.size() == 0) continue;
    if (line[0] == "end") return;
    else if (line[0] == "capacity") {
      electronHeatCapacity_ = str2dbl(line[1]);
      parameters["electron_heat_capacity"] = electronHeatCapacity_;
    }
    else {
      throw ATC_Error(0, "unrecognized material function: " + line[0]);
    }
  }
}
ElectronPhononExchangeLinear::ElectronPhononExchangeLinear(
  fstream &fileId, map<string,double> & parameters) 
  : ElectronPhononExchange(),
  exchangeCoef_(0)
{
  if (!fileId.is_open()) throw ATC_Error("cannot open material file");
  vector<string> line;
  while(fileId.good()) {
    command_line(fileId, line);
    if (line.size() == 0) continue;
    if (line[0] == "end") return;
    else if (line[0] == "coefficient") {
      exchangeCoef_ = str2dbl(line[1]);
      parameters["electron_phonon_exchange_coefficient"] = exchangeCoef_;
    }
    else {
      throw ATC_Error( "unrecognized material function "+line[0]);
    }
  }
}
Example #19
0
// ==================================================================================================
bool c4s::search_file(fstream &target, const string &needle)
/*!  Uses Boyer-Moore algorithm to search for a text in a given stream. Stream needs to be
  opened before this function is called. Search begins from the current position. If match is found
  the file pointer is positioned to the start of the next needle.
  On error an exception is thrown.

  \param target Opened file stream to search for.
  \param needle String that should be found
  \retval bool True if needle was found, false if not.
*/
{
    const SIZE_T BMAX = 0x1000;
    char buffer[BMAX];
    streamsize tg;
    SIZE_T br, boffset, total_offset, overlap=0;
    SIZE_T nsize = needle.size();
    if(!target.good())
        throw c4s_exception("search_file: given stream does not have 'good' status.");
    if(nsize >= BMAX)
        throw c4s_exception("search_file: size of search text exceeds internal read buffer size.");
    tg = target.tellg();
    if(tg<0)
        throw c4s_exception("search_file: unable to get file position information.");
    total_offset = SIZE_T(tg);
    do {
        target.read(buffer+overlap,BMAX-overlap);
        br = SIZE_T(target.gcount());
        if(search_bmh((unsigned char*)buffer, br+overlap, (unsigned char*)needle.c_str(), nsize, &boffset)) {
            target.clear();
            target.seekg(total_offset+boffset,ios_base::beg);
            return true;
        }
        total_offset += br;
        memcpy(buffer, buffer+BMAX-nsize, nsize);
        if(!overlap) {
            overlap = nsize;
            total_offset -= nsize;
        }
    }while(!target.eof());
    return false;
}
Example #20
0
int main(int argc, char* argv[]) {
	//Determine the number of threads to use
	if (USE_MULTIPLE_THREADS) {
		SYSTEM_INFO SysInfo;
		GetSystemInfo(&SysInfo);
		NumThreads = SysInfo.dwNumberOfProcessors;
		if (NumThreads > MAXTHREADS)
			NumThreads = MAXTHREADS;
	} else
		NumThreads = 1;

	string resultFileName =
		"wynik_" + TEST_NAME + "_" + to_string(NSIZE) + "_"
		+ to_string(RSIZE) + "_" + to_string(NumThreads) + ".txt";

	fileStream.open(resultFileName, std::ios::out | std::ios::trunc);
	if (!fileStream.good()) {
		fprintf(stderr, "Nie mozna otworzyc pliku wyniku %s\n", resultFileName);
	}


	fileStream << "File: " << resultFileName << "\n";
	printf("%s\n\n", resultFileName);

	initialize_matrices();
	multiply_matrices_IJK_sequence();
	start = (double)clock() / CLK_TCK;
	multiply_matrices_JKI();
	print_elapsed_time("JKI3");

	initialize_matricesZ();
	multiply_matrices_IJK_sequence();
	start = (double)clock() / CLK_TCK;
	multiply_matrices_IJK6();
	print_elapsed_time("IJK6");

	fileStream.close();
	system("PAUSE");
	return(0);
}
Example #21
0
//(TABLICA -> PLIK) Definicja funkcji zapisującej dane z tablicy do pliku "studenci.dat"
void zapiszTabliceDoPliku(string FILE_NAME, Student *tablica, int liczbaStruktur){

	studenci.open(FILE_NAME, ios::out);

	//Sprawdzenie czy plik został otwarty poprawnie
	if (studenci.good() == true) {
		//Pętla wczytująca i zapisująca w pliku "studenci.dat" imiona i nazwiska studentów (oprócz ostatniego wpisu) - z znakiem nowej linii "\n" na końcu
		for (int i = 0; i < (liczbaStruktur - 1); i++){

			//Zapisanie z struktur imion i nazwisk do pliku "studenci.dat" 
			studenci << tablica[i].imie << " " << tablica[i].nazwisko << " " << tablica[i].rokStudiow << "\n";
		
		}

		//Dodanie ostatniego wpisu (bez znaku nowej linii \n")
		studenci << tablica[liczbaStruktur - 1].imie << " " << tablica[liczbaStruktur - 1].nazwisko << " " << tablica[liczbaStruktur - 1].rokStudiow;

		//Zamknięcie pliku "studenci.dat" otwartego w trybie "wyjście/zapis"
		studenci.close();
	}
	//Usunięcie tablicy
	delete[] tablica;
}
Example #22
0
//(PLIK -> TABLICA) Definicja funkcji wczytującej informacje o studentach z pliku "studenci.dat" do tablicy;
tuple<Student *, int> wczytajPlikDoTablicy(string FILE_NAME){

	//Otworzenie pliku "studenci.dat" w trybie "wejście/odczyt"
	
	studenci.open(FILE_NAME, ios::in);
		
	//Sprawdzenie czy plik został otwarty poprawnie
	if (studenci.good() == true) {
		int liczbaStruktur = 0;
		string linia;
		
		//Pętla zliczająca liczbę linii - rekordów
		while (getline(studenci, linia)) {
			liczbaStruktur++;
		}

		//Powrót do początku pliku tekstowego
		studenci.clear();
		studenci.seekg(0, ios::beg);

		//Utworzenie tablicy o zadanej liczbie struktur typu student
		Student *tablica = new Student[liczbaStruktur];

		//Pętla zapisująca dane z pliku do struktur;
		int i = 0;

		while (!studenci.eof()) {
			studenci >> tablica[i].imie >> tablica[i].nazwisko >> tablica[i].rokStudiow;
			i++;
		}

		//Zamknięcie pliku "studenci.dat" otwartego w trybie "wejście/odczyt"
		studenci.close();

		//Funkcja zwraca dwa wyniki: tablicę z danymi oraz jej wielkość;
		return make_tuple((Student *)tablica, liczbaStruktur);
	}
Example #23
0
//When called in a loop, implements end-host send file functionality
void hostTryToSend(void) {
	static enum {
		STATE_LOOKFORFILE,
		STATE_FOUNDFILE,
		STATE_SENDPACKET,
		STATE_TRYAGAIN,
		STATE_FINISHED,
		STATE_IDLE
	} state = STATE_LOOKFORFILE;
	static fstream sendFile;
	static u_int32_t destIP;
	static u_int16_t srcPort, destPort;
	static u_int8_t buffer[PAYLOAD_LEN] = "";
	static int bufLen;
	static u_int16_t sequence = 0; //host byte order
	static int totalBytes = 0;
	char tempDestIP[32] = "";
	int sendResult;
	
	switch(state) {
		case STATE_LOOKFORFILE:
			sendFile.open("send.txt", fstream::in);
			if(sendFile.is_open()) {
				state = STATE_FOUNDFILE;
			}
			else {
				break;
			}
		case STATE_FOUNDFILE:
			sendFile.getline((char*)buffer, PAYLOAD_LEN-1);
			sscanf((char*)buffer, "%s %hu %hu", tempDestIP, &srcPort, &destPort);
			destIP = strIPtoBin(tempDestIP);
			srcPort = htons(srcPort);
			destPort = htons(destPort);
			state = STATE_SENDPACKET;
		case STATE_SENDPACKET:
			if(sendFile.good()) {
				bufLen = 0;
				memset(buffer, 0, PAYLOAD_LEN);
				
				sendFile.read((char*)buffer, PAYLOAD_LEN);
				bufLen = sendFile.gcount();
				sendResult = hostSendPacket(buffer, bufLen, destIP, srcPort, destPort, htons(sequence));
				if(sendResult == 0) {
					state = STATE_TRYAGAIN;
				}
				else {
					totalBytes += bufLen;
					sequence++;
				}
			}
			else {
				state = STATE_FINISHED;
			}
			break;
		case STATE_TRYAGAIN:
			sendResult = hostSendPacket(buffer, bufLen, destIP, srcPort, destPort, htons(sequence));
			if(sendResult == 1) {
				sequence++;
				totalBytes += bufLen;
				state = STATE_SENDPACKET;
			}
			break;
		case STATE_FINISHED:
			cout<<"File transmitted."<<endl
				<<"Size: "<<totalBytes<<" bytes."<<endl
				<<"Packets trasmitted: "<<sequence<<endl;
			state = STATE_IDLE;
			break;
		case STATE_IDLE:
			break;
	}
}
Example #24
0
void clGeometryReader::ReadGeometry(fstream &file, clGeometry &geometry) const
{
  int numberSurfaces = 0;
  int EndOfBlock     = 0;

  // Read line
  char line[LINE_SIZE];
  file.getline(line, LINE_SIZE);

  while(!file.eof() && file.good() && !EndOfBlock)
  {
    // Check first character in trimmed line
    switch(*strtrim(line))
    {
      case '#':
      case '*':
        // Comment line
        file.getline(line, LINE_SIZE);
        break;
      case '$':
      case '&':
      {
        // Block specifier
        int blockCommand = GetBlockSpec(line);

        switch(blockCommand)
        {
          case UNKNOWN_SPEC:
            throw clExceptionTree("clGeometryReader", "ReadGeometry", "Unknown block specifier.");
            break;
          case POINT_SPEC:
            // Start of point block
            throw clExceptionTree("clGeometryReader", "ReadGeometry", "Unexpected start of block POINT.");
            break;
          case PATCH_SPEC:
            // Start of patch block
            throw clExceptionTree("clGeometryReader", "ReadGeometry", "Unexpected start of block PATCH.");
            break;
          case SURFACE_SPEC:
          {
            // Start of surface block
            clSurface *surface = new clSurface(numberSurfaces++);

            ReadSurface(file, *surface);
            geometry.AddSurface(surface);

            file.getline(line, LINE_SIZE);
            break;
          }
          case GEOMETRY_SPEC:
            // Start of geometry block
            throw clExceptionTree("clGeometryReader", "ReadGeometry", "Unexpected start of block GEOMETRY.");
            break;
          case END_SPEC:
            // End of geometry block specification
            EndOfBlock = 1;
            break;
          default:
            throw clExceptionTree("clGeometryReader", "ReadGeometry", "Function GetBlockSpec returned unknown value.");
            break;
        }

        break;
      }
      case '/':
        // End of geometry block specification
        EndOfBlock = 1;
        break;
      default:
        file.getline(line, LINE_SIZE);
        break;
    }
  }
}
Example #25
0
void clGeometryReader::ReadSurface(fstream &file, clSurface &surface) const
{
  int EndOfBlock    = 0;

  // Read line
  char line[LINE_SIZE];
  file.getline(line, LINE_SIZE);

  while(!file.eof() && file.good() && !EndOfBlock)
  {
    // Check first character in trimmed line
    switch(*strtrim(line))
    {
      case '#':
      case '*':
        // Comment line
        file.getline(line, LINE_SIZE);
        break;
      case '$':
      case '&':
      {
        // Block specifier
        int blockCommand = GetBlockSpec(line);

        switch(blockCommand)
        {
          case UNKNOWN_SPEC:
            throw clExceptionTree("clGeometryReader", "ReadSurface", "Unknown block specifier.");
            break;
          case POINT_SPEC:
          {
            // Start of point block
            dMatrix pointsX, pointsY, pointsZ;

            ReadPoints(file, pointsX, pointsY, pointsZ);
            surface.CreatePatches(pointsX, pointsY, pointsZ);

            file.getline(line, LINE_SIZE);
            break;
          }
          case PATCH_SPEC:
          {
            // Start of patch block
            clPatch *patch = new clPatch;

            ReadPatch(file, *patch);
            surface.AddPatch(patch);

            file.getline(line, LINE_SIZE);
            break;
          }
          case SURFACE_SPEC:
            // Start of surface block
            throw clExceptionTree("clGeometryReader", "ReadSurface", "Unexpected start of block SURFACE.");
            break;
          case GEOMETRY_SPEC:
            // Start of geometry block
            throw clExceptionTree("clGeometryReader", "ReadSurface", "Unexpected start of block GEOMETRY.");
            break;
          case END_SPEC:
            // End of geometry block specification
            EndOfBlock = 1;
            break;
          default:
            throw clExceptionTree("clGeometryReader", "ReadSurface", "Function GetBlockSpec returned unknown value.");
            break;
        }

        break;
      }
      case '/':
        // End of geometry block specification
        EndOfBlock = 1;
        break;
      default:
        file.getline(line, LINE_SIZE);
        break;
    }
  }
}
Example #26
0
void clGeometryReader::ReadPoints(fstream &file, dMatrix &pointsX, dMatrix &pointsY, dMatrix &pointsZ) const
{
  int         EndOfBlock;
  int         AllRead;
  char        line[LINE_SIZE];
  char       *ptrLine = line;
  const char *tkn     = " ;:";
  int         countData;
  int         rmax = 0;
  int         cmax = 0;

  // Read line
  file.getline(line, LINE_SIZE);

  EndOfBlock = 0;
  AllRead    = 0;
  countData  = 0;
  while(!file.eof() && file.good() && !EndOfBlock)
  {
    // Check first character in trimmed line
    switch(*strtrim(line))
    {
      case '#':
      case '*':
        // Comment line, read next line
        file.getline(line, LINE_SIZE);
        break;
      case '&':
      case '$':
      {
        // Block specifier
        int blockCommand = GetBlockSpec(line);

        switch(blockCommand)
        {
          case UNKNOWN_SPEC:
            throw clExceptionTree("clGeometryReader", "ReadPoints", "Unknown block specifier.");
            break;

          case POINT_SPEC:
            throw clExceptionTree("clGeometryReader", "ReadPoints", "Unexpected start of block POINT.");
            break;

          case PATCH_SPEC:
            throw clExceptionTree("clGeometryReader", "ReadPoints", "Unexpected start of block PATCH.");
            break;

          case SURFACE_SPEC:
            throw clExceptionTree("clGeometryReader", "ReadPoints", "Unexpected start of block SURFACE.");
            break;

          case GEOMETRY_SPEC:
            throw clExceptionTree("clGeometryReader", "ReadPoints", "Unexpected start of block GEOMETRY.");
            break;

          case END_SPEC:
            EndOfBlock = 1;
            break;

          default:
            throw clExceptionTree("clGeometryReader", "ReadPoints", "Function GetBlockSpec returned unknown value.");
            break;
        }

        break;
      }
      case '/':
        // End of block specifier
        EndOfBlock = 1;
        break;
      default:
        if(strlen(strtrim(line)) > 0)
        {
          // Data line
          countData++;

          // Matrix specifiers
          if(countData==1)
          {
            // column defines constant u-values
            ptrLine = strtok(line, tkn);
            cmax    = str2int(ptrLine);

            // row defines constant v-values
            ptrLine = strtok(NULL, tkn);
            rmax    = str2int(ptrLine);

            // Set matrix dimensions
            pointsX.SetNumberRows(rmax);
            pointsX.SetNumberColumns(cmax);
            pointsY.SetNumberRows(rmax);
            pointsY.SetNumberColumns(cmax);
            pointsZ.SetNumberRows(rmax);
            pointsZ.SetNumberColumns(cmax);
          }

          // Specification of the x-coordinates
          else if(countData>=2 && countData<(2+rmax))
          {
            int row = (countData-1);

            // Set first u-element in current v
            ptrLine = strtok(line, tkn);
            pointsX.SetElement(row, 1, str2double(ptrLine));

            // Set following u-elements in current v
            for(int c=2; c<=cmax; c++)
            {
              ptrLine = strtok(0, tkn);
              pointsX.SetElement(row, c, str2double(ptrLine));
            }
          }

          // Specification of the y-coordinates
          else if(countData>=(2+rmax) && countData<(2+rmax+rmax))
          {
            int row = (countData-1-rmax);

            // Set first u-element in current v
            ptrLine = strtok(line, tkn);
            pointsY.SetElement(row, 1, str2double(ptrLine));

            // Set following u-elements in current v
            for(int c=2; c<=cmax; c++)
            {
              ptrLine = strtok(0, tkn);
              pointsY.SetElement(row, c, str2double(ptrLine));
            }
          }

          // Specification of the z-coordinates
          else if(countData>=(2+rmax+rmax) && countData<(2+rmax+rmax+rmax))
          {
            int row = (countData-1-rmax-rmax);

            // Set first u-element in current v
            ptrLine = strtok(line, tkn);
            pointsZ.SetElement(row, 1, str2double(ptrLine));

            // Set following u-elements in current v
            for(int c=2; c<=cmax; c++)
            {
              ptrLine = strtok(0, tkn);
              pointsZ.SetElement(row, c, str2double(ptrLine));
            }
          }

          // Too much data
          else
          {
            throw clExceptionTree("clGeometryReader", "ReadPoints", "Too much data.");
          }

          if(countData==(1+rmax+rmax+rmax))
          {
            AllRead = 1;
          }
        }

        file.getline(line, LINE_SIZE);
        break;
    }
  }

  if(!EndOfBlock || !AllRead)
  {
    throw clExceptionTree("clGeometryReader", "ReadPoints", "Unexpected end while reading block POINT.");
  }
}
Example #27
0
void clGeometryReader::ReadPatch(fstream &file, clPatch &patch) const
{
  int          EndOfBlock;
  int          AllRead;
  char         line[LINE_SIZE];
  char         *ptrLine = line;
  const char   *tkn     = " ;:";
  int          countData;

  int     ID   = 0;
  char    type = 'B';
  dMatrix GX(4, 4);
  dMatrix GY(4, 4);
  dMatrix GZ(4, 4);

  // Read line
  file.getline(line, LINE_SIZE);

  EndOfBlock = 0;
  AllRead    = 0;
  countData  = 0;
  while(!file.eof() && file.good() && !EndOfBlock)
  {
    // Check first character in trimmed line
    switch(*strtrim(line))
    {
      case '#':
      case '*':
        // Comment line
        file.getline(line, LINE_SIZE);
        break;
      case '&':
      case '$':
      {
        // Block specifier
        int blockCommand = GetBlockSpec(line);

        switch(blockCommand)
        {
          case UNKNOWN_SPEC:
            throw clExceptionTree("clGeometryReader", "ReadPatch", "Unknown block specifier.");
            break;

          case PATCH_SPEC:
            throw clExceptionTree("clGeometryReader", "ReadPatch", "Unexpected start of block PATCH.");
            break;

          case SURFACE_SPEC:
            throw clExceptionTree("clGeometryReader", "ReadPatch", "Unexpected start of block SURFACE.");
            break;

          case GEOMETRY_SPEC:
            throw clExceptionTree("clGeometryReader", "ReadPatch", "Unexpected start of block GEOMETRY.");
            break;

          case END_SPEC:
            EndOfBlock = 1;
            break;

          default:
            throw clExceptionTree("clGeometryReader", "ReadPatch", "Function GetBlockSpec returned unknown value.");
            break;
        }

        break;
      }
      case '/':
        // End of block specifier
        EndOfBlock = 1;
        break;
      default:
        if(strlen(strtrim(line)) > 0)
        {
          // Data line
          countData++;
          switch(countData)
          {
            // ID Number
            case 1:
              ID      = str2int(line);
              AllRead = 0;
              break;

            // blendType
            case 2:
              if(chrloc('H', line) != -1)
              {
                type = 'H';
              }
              else if(chrloc('B', line) != -1)
              {
                type = 'B';
              }
              else
              {
                throw clExceptionTree("clGeometryReader", "ReadPatch", "Unknown blending type.");
              }
              break;

            // Matrix GX
            case 3:
            case 4:
            case 5:
            case 6:
              ptrLine = strtok(line, tkn);
              GX.SetElement(countData-2, 1, str2double(ptrLine));

              ptrLine = strtok(0, tkn);
              GX.SetElement(countData-2, 2, str2double(ptrLine));

              ptrLine = strtok(0, tkn);
              GX.SetElement(countData-2, 3, str2double(ptrLine));

              ptrLine = strtok(0, tkn);
              GX.SetElement(countData-2, 4, str2double(ptrLine));
              break;

            // Matrix GY
            case 7:
            case 8:
            case 9:
            case 10:
              ptrLine = strtok(line, tkn);
              GY.SetElement(countData-6, 1, str2double(ptrLine));

              ptrLine = strtok(0, tkn);
              GY.SetElement(countData-6, 2, str2double(ptrLine));

              ptrLine = strtok(0, tkn);
              GY.SetElement(countData-6, 3, str2double(ptrLine));

              ptrLine = strtok(0, tkn);
              GY.SetElement(countData-6, 4, str2double(ptrLine));
              break;

            // Matrix GZ
            case 11:
            case 12:
            case 13:
            case 14:
              ptrLine = strtok(line, tkn);
              GZ.SetElement(countData-10, 1, str2double(ptrLine));

              ptrLine = strtok(0, tkn);
              GZ.SetElement(countData-10, 2, str2double(ptrLine));

              ptrLine = strtok(0, tkn);
              GZ.SetElement(countData-10, 3, str2double(ptrLine));

              ptrLine = strtok(0, tkn);
              GZ.SetElement(countData-10, 4, str2double(ptrLine));

              if(countData == 14)
              {
                AllRead = 1;

                // Correct for right hand axis system when type is Bezier
                if(type=='B')
                {
                  GX.Transpose(); GX.MirrorColumns();
                  GY.Transpose(); GY.MirrorColumns();
                  GZ.Transpose(); GZ.MirrorColumns();
                }

                // Now create the patch
                patch.SetNumberID(ID);
                patch.SetGX(GX);
                patch.SetGY(GY);
                patch.SetGZ(GZ);
                patch.SetBlendType(type);
              }
              break;

            // Error
            default:
              throw clExceptionTree("clGeometryReader", "ReadPatch", "Wrong number of data lines.");
              break;
          }
        }

        file.getline(line, LINE_SIZE);
        break;
    }
  }

  if(!EndOfBlock || !AllRead)
  {
    throw clExceptionTree("clGeometryReader", "ReadPatch", "Unexpected end while reading block PATCH.");
  }
}
Example #28
0
//*********************************************************************
//  FUNCTION:     OpenInputFile
//  DESCRIPTION:  Open the input text file.
//  INPUT:
//      Parameters:
//        std::string filename - Path to the input file.
//        std::fstream file - The file object to use when opening the
//                            input file.
//  OUTPUT:  
//      Return Val: Boolean indicating success of the file open
//                  operation.
//      Parameters:
//        std::fstream file - Initialized with the input file open on
//                            success.
//  PERFORMANCE:  f(n) = k
//**********************************************************************
bool OpenInputFile(string filename, fstream& file) {

  file.open(filename.c_str(), fstream::in);

  return(file.good());
} // OpenInputFile
Example #29
0
 bool Broken() override { return !iofile.good(); }
Example #30
0
	bool operator()() {
		return file.good();
	}