示例#1
0
bool 
bin_loader::load ( std::string const& filename, std::shared_ptr<beziervolumeobject> const& bptr )
{
  try {
    boost::filesystem::path inputfile ( filename );

    if ( !boost::filesystem::exists ( inputfile ) ) {
      throw std::runtime_error ( filename + " doesn't exists." );
    }

    std::string extension = boost::filesystem::extension ( inputfile );
    if ( extension != ".bin" ) {
      throw std::runtime_error ( "File not in binary format." );
    }

    std::fstream ifstr ( inputfile.string().c_str(), std::ios::in | std::ios_base::binary );
    bptr->read(ifstr);
    bptr->parent()->name(filename);

    ifstr.close();
    std::cerr << "Loading " << filename << " succeed." << std::endl;
    return true;
  } catch ( std::exception& e ) {
    std::cerr << "Loading " << filename << " failed. " << e.what() << std::endl;
    return false;
  }
}
示例#2
0
    // Read file contents into a buffer
    inline std::vector<char> read_file(const boost::filesystem::path& path)
    {
        std::ifstream ifstr(path.string(),
                            std::ifstream::in | std::ios::binary);
        if (!ifstr.is_open())
        {
            throw std::runtime_error("Could not open file for reading: " +
                                     path.string());
        }

        ifstr.unsetf(std::ios::skipws);

        ifstr.seekg(0, std::ios::end);
        const auto file_size = ifstr.tellg();
        ifstr.seekg(0, std::ios::beg);

        auto contents = std::vector<char>();
        contents.reserve(file_size);

        contents.insert(begin(contents),
                        std::istream_iterator<unsigned char>(ifstr),
                        std::istream_iterator<unsigned char>());
        ifstr.close();
        return contents;
    }
示例#3
0
/* get DISPLAY variable of a process */
char *get_display(pid_t pid) {
    static char buf[1024];

    sprintf(buf, "/proc/%d/environ", pid);

    std::ifstream ifstr(buf);
    if (ifstr.fail()) return 0;
    /* message("reading %s...", fname); */

    char * dpy = 0;
    while (!ifstr.eof()) {
        ifstr.getline(buf, sizeof buf - 1, '\0');
        if (ifstr.fail()) {
            syslog(LOG_ERR, "getline: %m");
            return 0;        /* read error */
        }
        if (!strncmp("DISPLAY=", buf, 8)) {
            int l = strlen(buf + 8);
            if (l >= 2 && l < (int) sizeof buf - 1) {
                dpy = new char[ l+2 ];
                strcpy(dpy," ");
                strcat(dpy, buf + 8); /* returns " "+dpy */
                /* message("- %s",dpy); */
            }
            break;
        }
    }
    return dpy;
}
示例#4
0
文件: StockReply.C 项目: ReWeb3D/wt
::int64_t StockReply::contentLength()
{
  std::string full_path(configuration().errRoot()
			+ stock_replies::toName(status()));
  std::string original_url;
  std::string content = "";
  std::string line;
  size_t clen = content_.length();
  std::ifstream ifstr(full_path.c_str(), std::ios::in | std::ios::binary);

  while (ifstr.good() && !ifstr.eof()) {
    std::getline(ifstr, line);
    size_t index = 0;

    while ((index = line.find("<-- SPECIAL CONTENT -->", index)) != line.npos) {
      line.replace(index,sizeof("<-- SPECIAL CONTENT -->")-1, content_);
      index += clen;
    }

    index = line.find("<-- ORIGINAL URL -->");

    if (index != line.npos) {
      stock_replies::buildOriginalURL(request_, original_url);
      clen = original_url.length();

      do {
	line.replace(index,sizeof("<-- ORIGINAL URL -->")-1, original_url);
	index += clen;
      } while((index = line.find("<-- ORIGINAL URL -->", index) != line.npos));

    }

    index = line.find("<-- ORIGINAL URL ESCAPED -->");

    if (index != line.npos) {
      if (original_url.empty())
	stock_replies::buildOriginalURL(request_, original_url);

      std::string escapedUrl = Wt::Utils::urlEncode(original_url);
      clen = escapedUrl.length();

      do {
	line.replace(index,sizeof("<-- ORIGINAL URL ESCAPED -->") - 1,
		     escapedUrl);
	index += clen;
      } while((index = line.find("<-- ORIGINAL URL ESCAPED -->", index)
	       != line.npos));
    }
    content += line + "\r\n";
  }
  ifstr.close();

  if (content.empty())
    content_ = stock_replies::toText(status()) + content_;
  else
    content_ = content;

  return content_.length();
}
void sRunTest(const string &sTestName, const STestInfo & testInfo, bool keep)
{
    cerr << "Testing " << testInfo.mInFile.GetName() << " against " <<
        testInfo.mOutFile.GetName() << " and " <<
        testInfo.mErrorFile.GetName() << endl;

    string logName = CDirEntry::GetTmpName();
    CErrorLogger logger(logName);

    CGvfReader reader(0);
    CNcbiIfstream ifstr(testInfo.mInFile.GetPath().c_str());

    typedef CGff2Reader::TAnnotList ANNOTS;
    ANNOTS annots;
    try {
        reader.ReadSeqAnnots(annots, ifstr, &logger);
    }
    catch (...) {
        BOOST_ERROR("Error: " << sTestName << " failed during conversion.");
        ifstr.close();
        return;
    }

    string resultName = CDirEntry::GetTmpName();
    CNcbiOfstream ofstr(resultName.c_str());
    for (ANNOTS::iterator cit = annots.begin(); cit != annots.end(); ++cit){
        ofstr << MSerial_AsnText << **cit;
        ofstr.flush();
    }
    ifstr.close();
    ofstr.close();

    bool success = testInfo.mOutFile.CompareTextContents(resultName, CFile::eIgnoreWs);
    if (!success) {
        CDirEntry deResult = CDirEntry(resultName);
        if (keep) {
            deResult.Copy(testInfo.mOutFile.GetPath() + "." + extKeep);
        }
        deResult.Remove();
        CDirEntry(logName).Remove();
        BOOST_ERROR("Error: " << sTestName << " failed due to post processing diffs.");
    }
    CDirEntry(resultName).Remove();

    success = testInfo.mErrorFile.CompareTextContents(logName, CFile::eIgnoreWs);
    CDirEntry deErrors = CDirEntry(logName);
    if (!success  &&  keep) {
        deErrors.Copy(testInfo.mErrorFile.GetPath() + "." + extKeep);
    }
    deErrors.Remove();
    if (!success) {
        BOOST_ERROR("Error: " << sTestName << " failed due to error handling diffs.");
    }
};
示例#6
0
bool read_file(std::string const& file, std::string& out_text)
{
    std::ifstream ifstr(file);
    if (!ifstr)
        return false;

    std::string line;
    while (std::getline(ifstr, line)) {
        out_text.append(line + "\n");
    }
    return true;
} 
示例#7
0
void stctJOB:: read_from_csv(int pDESIRED_ID){
	
	stctITEM objITEM;
	std:: ifstream ifstr ("./csvs/jobs_list.csv", std:: ifstream:: in);
	std:: string line;
	std:: vector<std:: string> current_JOB;
	
	while ( std:: getline(ifstr, line) ) {
		
		current_JOB = split (line);
		if ( stoi(current_JOB[0]) == pDESIRED_ID) { break; }
	}	
	if ( stoi(current_JOB[0]) != pDESIRED_ID) {
		
		std:: cout << "No matching item ID.\n";
	}
	else {
		objSTATSMAX.ATK = std:: stoi (current_JOB[7]);
		objSTATSMAX.DEF = std:: stoi (current_JOB[8]);
		objSTATSMAX.MAG = std:: stoi (current_JOB[9]);
		objSTATSMAX.SPD = std:: stoi (current_JOB[10]);
		objSTATSMAX.RES = std:: stoi (current_JOB[11]);
		objSTATSMAX.SKL = std:: stoi (current_JOB[12]);
		objSTATSMAX.LUK = std:: stoi (current_JOB[13]);
		objSTATSMAX.HP	= std:: stoi (current_JOB[21]);
		objSTATSMIN.ATK = std:: stoi (current_JOB[14]);
		objSTATSMIN.DEF = std:: stoi (current_JOB[15]);
		objSTATSMIN.MAG = std:: stoi (current_JOB[16]);
		objSTATSMIN.SPD = std:: stoi (current_JOB[17]);
		objSTATSMIN.RES = std:: stoi (current_JOB[18]);
		objSTATSMIN.SKL = std:: stoi (current_JOB[19]);
		objSTATSMIN.LUK = std:: stoi (current_JOB[20]);
		objSTATSMIN.HP	= std:: stoi (current_JOB[22]);
		objJOBGROWTHRATES.ATK = std:: stoi(current_JOB[23]);
		objJOBGROWTHRATES.DEF = std:: stoi(current_JOB[24]);
		objJOBGROWTHRATES.MAG = std:: stoi(current_JOB[25]);
		objJOBGROWTHRATES.SPD = std:: stoi(current_JOB[26]);
		objJOBGROWTHRATES.RES = std:: stoi(current_JOB[27]);
		objJOBGROWTHRATES.SKL = std:: stoi(current_JOB[28]);
		objJOBGROWTHRATES.LUK = std:: stoi(current_JOB[29]);
		objJOBGROWTHRATES.HP  = std:: stoi(current_JOB[30]);
		job_name = current_JOB[1];
		can_fly = std:: stoi (current_JOB[4]);
		can_swim = std:: stoi (current_JOB[5]);	
		movement = std:: stoi (current_JOB[6]);		
		primary_weapon = std:: stoi (current_JOB[2]);					
		secondary_weapon = std:: stoi (current_JOB[3]);
	}
}
示例#8
0
文件: if.c 项目: Aearsis/plotnetcfg
int if_add_warning(struct if_entry *entry, char *fmt, ...)
{
    va_list ap;
    char *warn;
    int err = ENOMEM;

    va_start(ap, fmt);
    entry->warnings++;
    if (vasprintf(&warn, fmt, ap) < 0)
        goto out;
    err = label_add(&entry->ns->warnings, "%s: %s", ifstr(entry), warn);
    free(warn);
out:
    va_end(ap);
    return err;
}
示例#9
0
STLFile::STLFile( const std::string &filename,
		  double vertex_matching_eps, 
		  double signed_volume_eps )
    : _filename(filename), _solid(vertex_matching_eps, signed_volume_eps)
{
    ibsimu.message( 1 ) << "Reading STL-file \'" << filename << "\'\n";
    ibsimu.inc_indent();

    std::ifstream ifstr( filename.c_str(), std::ios_base::binary );
    if( !ifstr.good() )
	throw( Error( ERROR_LOCATION, "Couldn't open file \'" + filename + "\'" ) );

    /* Check if ascii
     * Ascii files start with "solid XXX\n", on first line where XXX is free
     * form text. Second line starts with "facet normal" with possible leading whitespace
     * Binary files have free form 80 byte header
     */
    _ascii = false;
    char buf[1024];
    ifstr.read( buf, 1024 );
    std::streamsize c = ifstr.gcount();
    if( c > 6 && !strncasecmp( buf, "solid ", 6 ) ) {
	// Might be ascii, seek next line
	int a = 6;
	while( a < c && buf[a] != '\n' ) a++;
	while( a < c && isspace(buf[a]) ) a++;
	if( a+12 < c && !strncasecmp( &buf[a], "facet normal", 12 ) )
	    _ascii = true;
    }

    // Read triangle data
    ifstr.clear(); // Clear possible eofbit/failbit
    ifstr.seekg( 0 );
    if( _ascii )
	read_ascii( ifstr );
    else
	read_binary( ifstr );
    ifstr.close();

    // Convert to vertex triangle data
    build_vtriangle_data();
    _solid.check_data();
    _tri.clear();

    ibsimu.dec_indent();
}
示例#10
0
int _tmain(int argc, _TCHAR* argv[])
{
	std::ifstream ifstr("input.txt");
	int v_num, e_num;
	ifstr >> v_num >> e_num; // количество вершин, количество ребер с весом (откуда, куда)
	graph.resize(v_num);
	for (int i = 0; i < e_num; ++i) {
		int from_vertex, to_vertex;
		ifstr >> from_vertex >> to_vertex;
		graph[from_vertex].push_back(to_vertex);
	}

	DFS(0);

	getchar();
	return 0;
}
示例#11
0
    inline ews::message make_fake_message(const char* xml = nullptr)
    {
        typedef rapidxml::xml_document<> xml_document;

        std::vector<char> buf;

        if (xml)
        {
            // Load from given C-string

            std::copy(xml, xml + std::strlen(xml), std::back_inserter(buf));
            buf.push_back('\0');
        }
        else
        {
            // Load from file

            const auto assets = boost::filesystem::path(
                ews::test::global_data::instance().assets_dir);
            const auto file_path =
                assets / "undeliverable_test_mail_get_item_response.xml";
            std::ifstream ifstr(file_path.string(),
                                std::ifstream::in | std::ios::binary);
            if (!ifstr.is_open())
            {
                throw std::runtime_error("Could not open file for reading: " +
                                         file_path.string());
            }
            ifstr.unsetf(std::ios::skipws);
            ifstr.seekg(0, std::ios::end);
            const auto file_size = ifstr.tellg();
            ifstr.seekg(0, std::ios::beg);
            buf.reserve(file_size);
            buf.insert(begin(buf), std::istream_iterator<char>(ifstr),
                       std::istream_iterator<char>());
            ifstr.close();
        }

        xml_document doc;
        doc.parse<0>(&buf[0]);
        auto node = ews::internal::get_element_by_qname(
            doc, "Message", ews::internal::uri<>::microsoft::types());
        return ews::message::from_xml_element(*node);
    }
示例#12
0
	string load_string( const string& filename )
	{
#if 0
		// read file contents into char array
		FILE* f = fopen( filename.c_str(), "rb" );
		flut_error_if( f == NULL, "Could not open " + quoted( filename ) );

		fseek( f, 0, SEEK_END );
		int file_len = ftell( f );
		rewind( f );

		string s( file_len, '\0' );
		fread( reinterpret_cast< void* >( &s[ 0 ] ), sizeof( char ), file_len, f );

		return s;
#else
		// this method uses a stringbuf, which may be slower but more stable
		std::ifstream ifstr( filename );
		std::stringstream buf;
		buf << ifstr.rdbuf();
		return buf.str();
#endif
	}
void sUpdateCase(CDir& test_cases_dir, const string& test_name)
{   
    string input = CDir::ConcatPath( test_cases_dir.GetPath(), test_name + "." + extInput);
    string output = CDir::ConcatPath( test_cases_dir.GetPath(), test_name + "." + extOutput);
    string errors = CDir::ConcatPath( test_cases_dir.GetPath(), test_name + "." + extErrors);
    if (!CFile(input).Exists()) {
         BOOST_FAIL("input file " << input << " does not exist.");
    }
    string test_base, test_type;
    NStr::SplitInTwo(test_name, ".", test_base, test_type);
    cerr << "Creating new test case from " << input << " ..." << endl;

    CErrorLogger logger(errors);

    //get a scope
    CRef<CObjectManager> pObjMngr = CObjectManager::GetInstance();
    CGBDataLoader::RegisterInObjectManager(*pObjMngr);
    CRef<CScope> pScope(new CScope(*pObjMngr));
    pScope->AddDefaults();

    //get a writer object
    CNcbiIfstream ifstr(input.c_str(), ios::binary);
    CObjectIStream* pI = CObjectIStream::Open(eSerial_AsnText, ifstr, eTakeOwnership);

    CNcbiOfstream ofstr(output.c_str());
    CBedGraphWriter* pWriter = sGetWriter(*pScope, ofstr);

    if (test_type == "annot") {
        CRef<CSeq_annot> pAnnot(new CSeq_annot);
        *pI >> *pAnnot;
        pWriter->WriteHeader();
        pWriter->WriteAnnot(*pAnnot);
        pWriter->WriteFooter();
        delete pWriter;
        ofstr.flush();
    }
示例#14
0
void sUpdateCase(CDir& test_cases_dir, const string& test_name)
{   
    string input = CDir::ConcatPath( test_cases_dir.GetPath(), test_name + "." + extInput);
    string output = CDir::ConcatPath( test_cases_dir.GetPath(), test_name + "." + extOutput);
    string errors = CDir::ConcatPath( test_cases_dir.GetPath(), test_name + "." + extErrors);
    if (!CFile(input).Exists()) {
         BOOST_FAIL("input file " << input << " does not exist.");
    }
    cerr << "Creating new test case from " << input << " ..." << endl;

    CErrorLogger logger(errors);
    CGvfReader reader(0);
    CNcbiIfstream ifstr(input.c_str());

    typedef CGff2Reader::TAnnotList ANNOTS;
    ANNOTS annots;
    try {
        reader.ReadSeqAnnots(annots, ifstr, &logger);
    }
    catch (...) {
        ifstr.close();
        BOOST_FAIL("Error: " << input << " failed during conversion.");
    }
    ifstr.close();
    cerr << "    Produced new error listing " << output << "." << endl;

    CNcbiOfstream ofstr(output.c_str());
    for (ANNOTS::iterator cit = annots.begin(); cit != annots.end(); ++cit){
        ofstr << MSerial_AsnText << **cit;
        ofstr.flush();
    }
    ofstr.close();
    cerr << "    Produced new ASN1 file " << output << "." << endl;

    cerr << " ... Done." << endl;
}
示例#15
0
// reads property maps from data files
bool get_fileprops(const char* pcFile, t_map& mapProps)
{
	std::ifstream ifstr(pcFile);
	if(!ifstr)
	{
		tl::log_err("Cannot open file \"", pcFile, "\".");
		return 0;
	}

	std::string strLine;
	while(std::getline(ifstr, strLine))
	{
		tl::trim(strLine);
		// only collect lines starting with "#"
		if(!strLine.size() || strLine[0] != '#')
			continue;
		// ignore comments starting with "##"
		if(strLine.size()>=2 && strLine[0]=='#' && strLine[1]=='#')
			continue;

		strLine = strLine.substr(1);
		std::pair<std::string, std::string> strKeyVal = 
			tl::split_first(strLine, std::string("="), 1);

		std::string& strKey = strKeyVal.first;
		std::string& _strVal = strKeyVal.second;

		if(!strKey.size())
			continue;


		std::vector<t_real> vecHKLE;
		tl::get_tokens<t_real>(_strVal, std::string(" \t"), vecHKLE);

		// value & error pair
		if(_strVal.find("+-") != std::string::npos)
		{
			std::pair<std::string, std::string> strValErr =
				tl::split_first(_strVal, std::string("+-"), 1, 1);

			std::string& strVal = strValErr.first;
			std::string& strErr = strValErr.second;

			//std::cout << strKey << ": " << strVal << ", " << strErr << std::endl;
			if(strVal.length())
			{
				t_real dVal = tl::str_to_var<t_real>(strVal);
				t_real dErr = tl::str_to_var<t_real>(strErr);

				mapProps.insert(t_map::value_type(strKey, {dVal, dErr}));
			}
		}
		// hklE values -> split them, e.g. "scan_dir = 0 0 0 1" -> "scan_dir_h = 0", ...
		else if(vecHKLE.size()==3 || vecHKLE.size()==4)
		{
			std::vector<std::string> vecSuffixes = {"_h", "_k", "_l", "_E"};

			std::size_t iNumCoords = std::min(vecSuffixes.size(), vecHKLE.size());
			for(std::size_t iCoord=0; iCoord<iNumCoords; ++iCoord)
			{
				std::string strNewKey = strKey + vecSuffixes[iCoord];
				mapProps.insert(t_map::value_type(strNewKey, {vecHKLE[iCoord], 0.}));
			}
		}
		else
		{
			tl::log_warn("Unknown key: \"", strKey, "\".");
			continue;
		}
	}

	return 1;
}
示例#16
0
文件: catior.cpp 项目: asdlei00/ACE
int
ACE_TMAIN (int argcw, ACE_TCHAR *argvw[])
{
  CORBA::ORB_var orb_var;
  try
    {
      Catior_i catior_impl;
      orb_var =  CORBA::ORB_init (argcw, argvw);
      CORBA::Boolean b = false;
      CORBA::Boolean have_argument = false;
      int opt;

      ACE_Get_Opt get_opt (argcw, argvw, ACE_TEXT ("f:n:x"));

      while ((opt = get_opt ()) != EOF)
        {
          // some arguments have been supplied
          have_argument = 1;
          switch (opt)
            {
            case 'n':
              {
                //  Read the CosName from the NamingService convert the
                //  object_ptr to a CORBA::String_var via the call to
                //  object_to_string.
                ACE_DEBUG ((LM_DEBUG,
                            "opening a connection to the NamingService\n"
                            "resolving the CosName %s\n",
                            get_opt.opt_arg ()));

                CORBA::Object_var server_object;

                try
                  {
                    // Find the Naming Service.
                    CORBA::Object_var naming_context_object =
                      orb_var->resolve_initial_references ("NameService");
                    CosNaming::NamingContextExt_var naming_context =
                      CosNaming::NamingContextExt::_narrow (naming_context_object.in ());

                    if (CORBA::is_nil (naming_context.in ()))
                    {
                      ACE_ERROR_RETURN ((LM_ERROR,
                                        "NameService cannot be resolved\n"),
                                      -1);
                    }

                    CosNaming::Name *name =
                      naming_context->to_name (ACE_TEXT_ALWAYS_CHAR (get_opt.opt_arg ()));

                    try
                      {
                        server_object = naming_context->resolve (*name);
                          if (CORBA::is_nil (server_object.in ()))
                          {
                            ACE_ERROR_RETURN ((LM_ERROR,
                                  "name is not resolved to a valid object\n"),
                                              -1);
                          }
                      }
                    catch (const CosNaming::NamingContext::NotFound& nf)
                      {
                        const ACE_TCHAR *reason;

                        switch (nf.why)
                          {
                            case CosNaming::NamingContext::missing_node:
                              reason = ACE_TEXT ("missing node");
                              break;
                            case CosNaming::NamingContext::not_context:
                              reason = ACE_TEXT ("not context");
                              break;
                            case CosNaming::NamingContext::not_object:
                              reason = ACE_TEXT ("not object");
                              break;
                            default:
                              reason = ACE_TEXT ("not known");
                              break;
                          }
                        ACE_ERROR_RETURN ((LM_ERROR,
                                  "%s cannot be resolved, exception reason = %s\n",
                                          get_opt.opt_arg (),
                                          reason),
                                        -1);
                      }
                    catch (const CosNaming::NamingContext::InvalidName&)
                      {
                        ACE_ERROR_RETURN ((LM_ERROR,
                                      "%s cannot be resolved, exception reason = "
                                          "Invalid Name"
                                          "\n",
                                          get_opt.opt_arg ()),
                                        -1);
                      }
                    catch (const CosNaming::NamingContext::CannotProceed&)
                      {
                        ACE_ERROR_RETURN ((LM_ERROR,
                                      "%s cannot be resolved, exception reason = "
                                          "Cannot Proceed"
                                          "\n",
                                          get_opt.opt_arg ()),
                                        -1);
                      }
                    catch (const CORBA::Exception&)
                      {
                        ACE_ERROR_RETURN ((LM_ERROR,
                                      "%s cannot be resolved, exception reason = "
                                          "Unexpected Exception"
                                          "\n",
                                          argvw[0]),
                                          -1);
                      }

                    ACE_CString aString;

                    aString = orb_var->object_to_string (server_object.in ());

                    ACE_DEBUG ((LM_DEBUG,
                                "\nhere is the IOR\n%C\n\n",
                                aString.rep ()));

                    ACE_CString str;
                    b = catior_impl.decode(aString, str);
                    ACE_DEBUG ((LM_DEBUG, "%s", str.c_str()));
                  }
                catch (const CORBA::Exception&)
                  {
                    ACE_ERROR_RETURN ((LM_ERROR,
                                      "%s cannot be resolved, exception reason = "
                                      "Unexpected Exception"
                                      "\n",
                                      argvw[0]),
                                      -1);
                  }

                if (b == 1)
                  ACE_DEBUG ((LM_DEBUG,
                              "catior returned true\n"));
                else
                  ACE_DEBUG ((LM_DEBUG,
                              "catior returned false\n"));
                break;
              }
            case 'f':
              {
                int have_some_input = 0;
                int decode_pass_count = 0;

                //  Read the file into a CORBA::String_var.
                ACE_DEBUG ((LM_DEBUG,
                            "reading the file %s\n",
                            get_opt.opt_arg ()));

#if !defined (ACE_LACKS_IOSTREAM_TOTALLY)
                ifstream ifstr (ACE_TEXT_ALWAYS_CHAR(get_opt.opt_arg ()));

                if (!ifstr.good ())
                  {
                    ifstr.close ();
                    ACE_ERROR_RETURN ((LM_ERROR,
                                      "%s "
                                      "-f %s "
                                      "\n"
                                      "Invalid IOR file nominated"
                                      "\n",
                                      argvw[0],
                                      get_opt.opt_arg ()),
                                      -1);
                  }

                while (!ifstr.eof())
                  {
                    ACE_CString aString;

                    have_some_input = 0;

                    while (!ifstr.eof ())
                      {
                        char ch = 0;
                        ifstr.get (ch);
                        if (ifstr.eof () || ch == '\n' || ch == '\r')
                          break;
                        aString += ch;
                        ++have_some_input;
                      }
#else
                FILE* ifstr = ACE_OS::fopen (get_opt.opt_arg (), ACE_TEXT ("r"));

                if (!ifstr || ferror (ifstr))
                  {
                    if (ifstr)
                      {
                      ACE_OS::fclose (ifstr);
                      }
                      ACE_ERROR_RETURN ((LM_ERROR,
                                        "%s "
                                        "-f %s "
                                        "\n"
                                        "Invalid IOR file nominated"
                                        "\n",
                                        argvw[0],
                                        get_opt.opt_arg ()),
                                        -1);
                  }

                while (!feof (ifstr))
                  {
                    char ch;
                    ACE_CString aString;

                    have_some_input = 0;

                    while (!feof (ifstr))
                      {
                        ch = ACE_OS::fgetc (ifstr);
                        if (ch == EOF || ch == '\n' || ch == '\r')
                          break;
                        aString += ch;
                        ++have_some_input;
                      }
#endif /* !defined (ACE_LACKS_IOSTREAM_TOTALLY) */
                    if (have_some_input == 0 || !aString.length())
                      {
                        if (!decode_pass_count)
                          {
                              ACE_ERROR_RETURN ((LM_ERROR,
                                                "%s "
                                                "-f %s "
                                                "\n"
                                                "Empty IOR file nominated"
                                                "\n",
                                                argvw[0],
                                                get_opt.opt_arg ()),
                                                -1);
                          }
                        else
                          {
                            ACE_DEBUG ((LM_DEBUG,
                                        "catior returned true\n"));
                            return 0;               // All done now
                          }
                      }

                    ++decode_pass_count;

                    ACE_DEBUG ((LM_DEBUG,
                                "\nhere is the IOR\n%C\n\n",
                                aString.rep ()));

                    ACE_CString str;
                    b = catior_impl.decode(aString, str);
                    ACE_DEBUG ((LM_DEBUG, "%s", str.c_str()));
                  }
                if (b == 1)
                  ACE_DEBUG ((LM_DEBUG,
                              "catior returned true\n"));
                else
                  ACE_DEBUG ((LM_DEBUG,
                              "catior returned false\n"));
#if !defined (ACE_LACKS_IOSTREAM_TOTALLY)
                ifstr.close ();
#else
                ACE_OS::fclose (ifstr);
#endif /* !defined (ACE_LACKS_IOSTREAM_TOTALLY) */
              }
              break;
            case 'x':
              {
                int have_some_input = 0;
                int decode_pass_count = 0;

                //  Read the input into a CORBA::String_var.
                ACE_DEBUG ((LM_DEBUG,
                            "reading from stdin\n"));

    #if !defined (ACE_LACKS_IOSTREAM_TOTALLY)
                if (!cin.good ())
                  {
                    ACE_ERROR_RETURN ((LM_ERROR,
                                      "%s "
                                      "-x"
                                      "\n"
                                      "Invalid input stream"
                                      "\n",
                                      argvw[0]),
                                      -1);
                  }

                while (!cin.eof())
                  {
                    ACE_CString aString;

                    have_some_input = 0;

                    while (!cin.eof ())
                      {
                        char ch = 0;
                        cin.get (ch);
                        if (cin.eof () || ch == '\n' || ch == '\r')
                          break;
                        aString += ch;
                        ++have_some_input;
                      }
#else
                FILE* ifstr = stdin;

                if (!ifstr || ferror (ifstr))
                  {
                    if (ifstr)
                      {
                      ACE_OS::fclose (ifstr);
                      }
                    ACE_ERROR_RETURN ((LM_ERROR,
                                      "%s "
                                      "-x"
                                      "\n"
                                      "Invalid input stream"
                                      "\n",
                                      argvw[0]),
                                      -1);
                  }

                while (!feof (ifstr))
                  {
                    char ch;
                    ACE_CString aString;

                    have_some_input = 0;

                    while (!feof (ifstr))
                      {
                        ch = ACE_OS::fgetc (ifstr);
                        if (ch == EOF || ch == '\n' || ch == '\r')
                          break;
                        aString += ch;
                        ++have_some_input;
                      }
#endif /* !defined (ACE_LACKS_IOSTREAM_TOTALLY) */

                    if (have_some_input == 0)
                      {
                        if (!decode_pass_count)
                          {
                            ACE_ERROR_RETURN ((LM_ERROR,
                                              "%s "
                                              "-x"
                                              "\n"
                                              "Empty input stream"
                                              "\n",
                                              argvw[0]),
                                              -1);
                          }
                        else
                          {
                            return 0;               // All done now
                          }
                      }

                    ++decode_pass_count;

                    ACE_DEBUG ((LM_DEBUG,
                                "\nhere is the IOR\n%C\n\n",
                                aString.rep ()));

                    ACE_CString str;
                    b = catior_impl.decode(aString, str);
                    ACE_DEBUG ((LM_DEBUG, "%s", str.c_str()));
                  }
                if (b == 1)
                  ACE_DEBUG ((LM_DEBUG,
                              "catior returned true\n"));
                else
                  ACE_DEBUG ((LM_DEBUG,
                              "catior returned false\n"));
              }
              break;
            case '?':
            case 'h':
            default:
              ACE_ERROR_RETURN ((LM_ERROR,
                                "Usage: %s "
                                "-f filename "
                                "-n CosName "
                                "\n"
                                "Reads an IOR "
                                "and dumps the contents to stdout "
                                "\n",
                                argvw[0]),
                                1);
            }
        }

        // check that some relevant arguments have been supplied
        if (have_argument == 0)
              ACE_ERROR_RETURN ((LM_ERROR,
                                "Usage: %s "
                                "-f filename "
                                "-n CosName "
                                "\n"
                                "Reads an IOR "
                                "and dumps the contents to stdout "
                                "\n",
                                argvw[0]),
                                1);
    }
  catch (const CORBA::Exception& ex)
    {
      ACE_DEBUG ((LM_DEBUG, "\nError:\n"));
      ex._tao_print_exception ("Exception in nsadd");
      orb_var->destroy ();
      return 1;
    }
  return 0;
}
示例#17
0
static int ifstate (int code, int val, int *err)
{
    static unsigned short T[IF_DEPTH];
    static unsigned short got_if[IF_DEPTH];
    static unsigned short got_else[IF_DEPTH];
    static unsigned short got_T[IF_DEPTH];
    static unsigned short indent;
    int i, ret = 0;

#if IFDEBUG
    fprintf(stderr, "ifstate: code = %s\n", ifstr(code));
#endif

    if (code == RELAX) {
	indent = 0;
    } else if (code == IFRESET) {
	indent = val;
    } else if (code == GETINDENT) {
	ret = indent;
    } else if (code == UNINDENT) {
	ret = --indent;
    } else if (code == SET_FALSE || code == SET_TRUE) {
	indent++;
	if (indent >= IF_DEPTH) {
	    gretl_errmsg_sprintf("IF depth (%d) exceeded", IF_DEPTH);
	    *err = E_DATA;
	} else {
	    T[indent] = got_T[indent] = (code == SET_TRUE);
	    got_if[indent] = 1;
	    got_else[indent] = 0;
	}
    } else if (code == SET_ELSE || code == SET_ELIF) {
	if (got_else[indent] || !got_if[indent]) {
	    unmatched_message(code);
	    *err = E_PARSE;
	} else {
	    got_else[indent] = (code == SET_ELSE);
	    if (T[indent]) {
		T[indent] = 0;
	    } else if (!got_T[indent]) {
		T[indent] = 1;
	    }
	}
    } else if (code == SET_ENDIF) {
	if (!got_if[indent] || indent == 0) {
	    unmatched_message(code);
	    *err = E_PARSE;
	} else {
	    got_if[indent] = 0;
	    got_else[indent] = 0;
	    got_T[indent] = 0;
	    indent--;
	}
    } else if (code == IS_FALSE || code == IS_TRUE) {
	for (i=1; i<=indent; i++) {
	    if (T[i] == 0) {
		ret = 1;
		break;
	    }
	}
	if (code == IS_TRUE) {
	    ret = !ret;
	}
    } 

#if IFDEBUG
    fprintf(stderr, "ifstate: returning %d (indent %d, err %d)\n", 
	    ret, indent, (err == NULL)? 0 : *err);
#endif

    return ret;
}
示例#18
0
int parseFormat(string ffname, ivector & tvec, svector & dnames, svector & delims, int *grpsize) {
  ifstream ifstr(ffname.c_str(), ios::in);
  if (ifstr.fail() || ifstr.eof()) {
    cerr << "couldnt open format file" << endl;
    throw;
  }
  char *next, *third, *newstr, *linebuf = new char[80];
  while (!ifstr.bad() && !ifstr.eof()) {
    ifstr.getline(linebuf, 80);
    if (strlen(linebuf) > 1) {
      next = strchr(linebuf, ' ');
      *next++ = 0;
      third = strchr(next, ' ');
      if (third)
	*third++ = 0;
      dnames.push_back(next);
      if (strncmp(linebuf, "int", 3) == 0) {
	tvec.push_back(ftype_int);
	delims.push_back("");
      } else if (strncmp(linebuf, "dint", 4) == 0) {
	tvec.push_back(ftype_dint);
	delims.push_back("");
      } else if (strncmp(linebuf, "qhex", 4) == 0) {
	tvec.push_back(ftype_qhex);
	delims.push_back("");
      } else if (strncmp(linebuf, "float", 5) == 0) {
	tvec.push_back(ftype_float);
	delims.push_back("");
      } else if (strncmp(linebuf, "double", 6) == 0) {
	tvec.push_back(ftype_double);
	delims.push_back("");
      } else if (strncmp(linebuf, "word", 4) == 0) {
	tvec.push_back(ftype_word);
	delims.push_back("");
      } else if (strncmp(linebuf, "string", 6) == 0) {
	tvec.push_back(ftype_string);
	ifstr.getline(linebuf, 80);
        newstr = new char[strlen(linebuf)+1];
        strcpy(newstr, linebuf);
	delims.push_back(newstr);
      } else if (strncmp(linebuf, "date", 4) == 0) {
	tvec.push_back(ftype_date);
	delims.push_back("");
      } else if (strncmp(linebuf, "mdate", 5) == 0) {
	tvec.push_back(ftype_mdate);
	delims.push_back("");
      } else if (strncmp(linebuf, "cmdate", 6) == 0) {
	tvec.push_back(ftype_cmdate);
	delims.push_back("");
      } else if (strncmp(linebuf, "dt", 2) == 0) {
	tvec.push_back(ftype_dt);
	delims.push_back("");
      } else if (strncmp(linebuf, "mdt", 3) == 0) {
	tvec.push_back(ftype_mdt);
	delims.push_back("");
      } else if (strncmp(linebuf, "group", 5) == 0) {
	sscanf(third, "%d", grpsize);
	tvec.push_back(ftype_group);
	delims.push_back("");
      } else if (strncmp(linebuf, "igroup", 6) == 0) {
	sscanf(third, "%d", grpsize);
	tvec.push_back(ftype_igroup);
	ifstr.getline(linebuf, 80);
	delims.push_back(linebuf);
      } else if (strncmp(linebuf, "digroup", 7) == 0) {
	sscanf(third, "%d", grpsize);
	tvec.push_back(ftype_digroup);
	ifstr.getline(linebuf, 80);
	delims.push_back(linebuf);
      } else {
        cerr << "couldnt parse format file line " << tvec.size()+1 << endl;
	throw;
      }
    }
  }
  return tvec.size();
  delete [] linebuf;
}