• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ readValue函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中readValue函数的典型用法代码示例。如果您正苦于以下问题:C++ readValue函数的具体用法?C++ readValue怎么用?C++ readValue使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了readValue函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: InputTemp

WebInputTemp::WebInputTemp(Params &p):
    InputTemp(p)
{

    ioDoc->friendlyNameSet("WebInputTemp");
    ioDoc->descriptionSet(_("Temperature input read from a web document"));
    ioDoc->paramAdd("url", _("URL where to download the document from.\n"
                             "If URL begins with file:// the data is read from the local file"),
                    IODoc::TYPE_STRING, true);
    ioDoc->paramAdd("file_type",_("File type of the document. Values can be xml, json or text."),
                    IODoc::TYPE_STRING, true);
    ioDoc->paramAdd("path",_("The path where to found the value. This value can take multiple values "
                             "depending on the file type. If file_type is JSON, the json file "
                             "downloaded will be read, and the informations will be extracted from "
                             "the path. for example weather[0]/description, try to read the "
                             "description value of the 1 element of the array of the weather object.\n"
                             "If file_type is XML, the path is an xpath expression; Look here for "
                             "syntax : http://www.w3schools.com/xsl/xpath_syntax.asp "
                             "If file_type is TEXT, the downloaded file is returned as "
                             "plain text file, and path must be in the form line/pos/separator "
                             "Line is read, and is split using separator as delimiters "
                             "The value returned is the value at pos in the split list. "
                             "If the separator is not found, the whole line is returned. "
                             "Example the file contains \n"
                             "10.0,10.1,10.2,10.3\n"
                             "20.0,20.1,20.2,20.3\n"
                             "If the path is 2/4/, the value returne wil be 20.3\n"),
                             IODoc::TYPE_STRING, true);

    cInfoDom("input") << "WebInputTemp::WebInputTemp()";
    Calaos::StartReadRules::Instance().addIO();

    // Add input to WebCtrl instance
    WebCtrl::Instance(p).Add(get_param("path"), readTime, [=]()
    {
        readValue();
        Calaos::StartReadRules::Instance().ioRead();
    });
}
开发者ID:expertisesolutions,项目名称:calaos_base,代码行数:39,代码来源:WebInputTemp.cpp


示例2: pthread_mutex_lock

int IioSensorBase::readEvents(sensors_event_t* data, int count)
{
    if (count < 1)
        return -EINVAL;

    pthread_mutex_lock(&mLock);
    int numEventReceived = 0;

    if (mHasPendingEvent) {
        mHasPendingEvent = false;
        if (mEnabled) {
            mPendingEvent.timestamp = getTimestamp();
            *data = mPendingEvent;
            numEventReceived++;
        }
        goto done;
    }

    iio_event_data const* event;

    while (count && mInputReader.readEvent(mDataFd, &event)) {
        int value;
        if (IIO_EVENT_CODE_EXTRACT_CHAN_TYPE(event->id) == mIioChanType) {
            if (mEnabled && readValue(&value)) {
                handleData(value);
                mPendingEvent.timestamp = event->timestamp;
                *data++ = mPendingEvent;
                count--;
                numEventReceived++;
            }
        }
        mInputReader.next();
    }

done:
    pthread_mutex_unlock(&mLock);
    return numEventReceived;
}
开发者ID:Khaon,项目名称:android_device_samsung_manta,代码行数:38,代码来源:IioSensorBase.cpp


示例3: in

EnumMap<OptionId, Options::Value> Options::readValues() {
  EnumMap<OptionId, Value> ret = defaults;
  ifstream in(filename);
  while (1) {
    char buf[100];
    in.getline(buf, 100);
    if (!in)
      break;
    vector<string> p = split(string(buf), {','});
    if (p.empty())
      continue;
    if (p.size() == 1)
      p.push_back("");
    OptionId optionId;
    if (auto id = EnumInfo<OptionId>::fromStringSafe(p[0]))
      optionId = *id;
    else
      continue;
    if (auto val = readValue(optionId, p[1]))
      ret[optionId] = *val;
  }
  return ret;
}
开发者ID:silidur,项目名称:keeperrl,代码行数:23,代码来源:options.cpp


示例4: init

bool Reader::readArray(Token& tokenStart) {
  Value init(arrayValue);
  currentValue().swapPayload(init);
  currentValue().setOffsetStart(tokenStart.start_ - begin_);
  skipSpaces();
  if (*current_ == ']') // empty array
  {
    Token endArray;
    readToken(endArray);
    return true;
  }
  int index = 0;
  for (;;) {
    Value& value = currentValue()[index++];
    nodes_.push(&value);
    bool ok = readValue();
    nodes_.pop();
    if (!ok) // error already set
      return recoverFromError(tokenArrayEnd);

    Token token;
    // Accept Comment after last item in the array.
    ok = readToken(token);
    while (token.type_ == tokenComment && ok) {
      ok = readToken(token);
    }
    bool badTokenType =
        (token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd);
    if (!ok || badTokenType) {
      return addErrorAndRecover(
          "Missing ',' or ']' in array declaration", token, tokenArrayEnd);
    }
    if (token.type_ == tokenArrayEnd)
      break;
  }
  return true;
}
开发者ID:robsonswiss,项目名称:OSVR-user-settings,代码行数:37,代码来源:json_reader.cpp


示例5: parseStructure

    bool parseStructure(VLXStructure* st)
    {
      std::string str;
      
      // tag
      if (!readString(str))
        return false;
      st->setTag(str.c_str());

      // ID
      if (!readString(str))
        return false;
      st->setID(str.c_str());

      // read key/value count
      long long count = 0;
      if (!readInteger(count))
        return false;

      // values
      for(int i=0; i<count; ++i)
      {
        VLXStructure::Value val;
        
        // key
        if (!readString(str))
          return false;
        val.setKey(str.c_str());

        // value
        if (!readValue(val.value()))
          return false;
        st->value().push_back(val);
      }
      
      return true;
    }
开发者ID:PaezRice,项目名称:VisualizationLibrary,代码行数:37,代码来源:VLXParserVLB.hpp


示例6: Hash

Hash* Parser::readHash()
{
    Tokenizer::TokenType tok = tokenizer->nextToken();
    if (tok != Tokenizer::TokenBeginGroup)
    {
        tokenizer->pushBack();
        return NULL;
    }

    Hash* hash = new Hash();

    tok = tokenizer->nextToken();
    while (tok != Tokenizer::TokenEndGroup)
    {
        if (tok != Tokenizer::TokenName)
        {
            tokenizer->pushBack();
            delete hash;
            return NULL;
        }
        string name = tokenizer->getNameValue();

        Value* value = readValue();
        if (value == NULL)
        {
            delete hash;
            return NULL;
        }
        
        hash->addValue(name, *value);

        tok = tokenizer->nextToken();
    }

    return hash;
}
开发者ID:jpcoles,项目名称:ZM,代码行数:36,代码来源:parser.cpp


示例7: QgsDebugMsg

void * QgsRasterNuller::readBlock( int bandNo, QgsRectangle  const & extent, int width, int height )
{
  QgsDebugMsg( "Entered" );
  if ( !mInput ) return 0;

  //QgsRasterDataProvider *provider = dynamic_cast<QgsRasterDataProvider*>( mInput->srcInput() );

  void * rasterData = mInput->block( bandNo, extent, width, height );

  QgsRasterInterface::DataType dataType =  mInput->dataType( bandNo ); 
  int pixelSize = mInput->typeSize( dataType ) / 8; 

  double noDataValue = mInput->noDataValue ( bandNo );

  for ( int i = 0; i < height; ++i )
  {
    for ( int j = 0; j < width; ++j )
    {
      int index = pixelSize * ( i * width + j );

      double value = readValue( rasterData, dataType, index );
  
      foreach ( NoData noData, mNoData )
      {
        if ( ( value >= noData.min && value <= noData.max ) ||
             doubleNear( value, noData.min ) ||
             doubleNear( value, noData.max ) )
        {
          writeValue( rasterData, dataType, index, noDataValue );
        }
      }
    }
  }

  return rasterData;
}
开发者ID:namhh,项目名称:Quantum-GIS,代码行数:36,代码来源:qgsrasternuller.cpp


示例8: while

void ConfigXml::readEntryElement(int *id)
{
    QString type = reader.attributes().value("type").toString();

    reader.readNext();
    while (!reader.atEnd()) {
        if (reader.isEndElement()) {
            reader.readNext();
            break;
        }

        if (reader.isStartElement()) {
            if (reader.name() == "entry") {
                readEntryElement(id);
            } else if (reader.name() == "value") {
                readValue(id, type);
            } else {
                skipUnknownElement();
            }
        } else {
            reader.readNext();
        }
    }
}
开发者ID:sriemer,项目名称:dmmctr,代码行数:24,代码来源:configxml.cpp


示例9: readInstructionFromBuffer

size_t readInstructionFromBuffer(const char* buf, Instruction* instr)
{
	size_t nRead = 0;

	instr->iType = *buf;
	buf += 2; nRead += 2;

	int nCol = instr->table->nCol;
	if (instr->iType == SQLITE_UPDATE) {
		nCol *= 2;
	}

	for (int i=0; i < nCol; i++) {
		sqlite_value* val_p = instr->values + i;
		size_t read = readValue(buf, val_p);
		if (read == 0) {
			return 0;
		}
		buf += read;
		nRead += read;
	}

	return nRead;
}
开发者ID:Lukas-W,项目名称:sqlitediff,代码行数:24,代码来源:patch.cpp


示例10: while

void VCalParser::readEvent()
{
	//qDebug() << "[calendar] reading event";
	//QTime time;

	QString key, val;
	TEvent event;

	//time.start();
	while( key != "END" && !atEnd ) {
		key = readKey();
		val = readValue();

		if( key == "UID" )				event.setUid(val);
		else if( key == "DESCRIPTION")  event.setDescription(val);
		else if( key == "SUMMARY")      event.setSummary(val);
		else if( key == "LOCATION")     event.setLocation(val);
		else if( key == "LAST-MODIFIED")event.setLastModified(decodeDate(val));
		else if( key == "CLASS")        event.setClass(val);
		else if( key == "STATUS")       event.setStatus(val);
		else if( key == "DTSTART" ||
				 key == "DTSTART;VALUE=DATE") {
			if( val.size() > 1 )		event.setStart(decodeDate(val));
		} else if( key == "DTEND" ||
				   key == "DTEND;VALUE=DATE") {
			if( val.size() > 1 )		event.setEnd(decodeDate(val));
		}

		// event is in the future
		if(event.getStart() > QDateTime::currentDateTime()) {
			if(event < nextEvent) nextEvent = event;
		}
	}

	m_events.append(event);
}
开发者ID:Raven24,项目名称:FCalendar,代码行数:36,代码来源:vcalparser.cpp


示例11: while

bool 
Reader::parse( const char *beginDoc, const char *endDoc, 
               Value &root,
               bool collectComments )
{
   begin_ = beginDoc;
   end_ = endDoc;
   collectComments_ = collectComments;
   current_ = begin_;
   lastValueEnd_ = 0;
   lastValue_ = 0;
   commentsBefore_ = "";
   errors_.clear();
   while ( !nodes_.empty() )
      nodes_.pop();
   nodes_.push( &root );
   
   bool successful = readValue();
   Token token;
   skipCommentTokens( token );
   if ( collectComments_  &&  !commentsBefore_.empty() )
      root.setComment( commentsBefore_, commentAfter );
   return successful;
}
开发者ID:AngryPowman,项目名称:smalltranslator,代码行数:24,代码来源:json_reader.cpp


示例12: isDeviceProperty

void MtpProperty::read(MtpDataPacket& packet) {
    mCode = packet.getUInt16();
    bool deviceProp = isDeviceProperty();
    mType = packet.getUInt16();
    mWriteable = (packet.getUInt8() == 1);
    switch (mType) {
        case MTP_TYPE_AINT8:
        case MTP_TYPE_AUINT8:
        case MTP_TYPE_AINT16:
        case MTP_TYPE_AUINT16:
        case MTP_TYPE_AINT32:
        case MTP_TYPE_AUINT32:
        case MTP_TYPE_AINT64:
        case MTP_TYPE_AUINT64:
        case MTP_TYPE_AINT128:
        case MTP_TYPE_AUINT128:
            mDefaultArrayValues = readArrayValues(packet, mDefaultArrayLength);
            if (deviceProp)
                mCurrentArrayValues = readArrayValues(packet, mCurrentArrayLength);
            break;
        default:
            readValue(packet, mDefaultValue);
            if (deviceProp)
                readValue(packet, mCurrentValue);
    }
    if (!deviceProp)
        mGroupCode = packet.getUInt32();
    mFormFlag = packet.getUInt8();

    if (mFormFlag == kFormRange) {
            readValue(packet, mMinimumValue);
            readValue(packet, mMaximumValue);
            readValue(packet, mStepSize);
    } else if (mFormFlag == kFormEnum) {
        mEnumLength = packet.getUInt16();
        mEnumValues = new MtpPropertyValue[mEnumLength];
        for (int i = 0; i < mEnumLength; i++)
            readValue(packet, mEnumValues[i]);
    }
}
开发者ID:clarkli86,项目名称:mini2440-mtp-server,代码行数:40,代码来源:MtpProperty.cpp


示例13: readValue

bool
SimpleProperties::Reader::next(){
  return readValue();
}
开发者ID:Baoxiyi-Github,项目名称:Mysql,代码行数:4,代码来源:SimpleProperties.cpp


示例14: readValue

int TestMain::readValue2(const int ver)
{
    const int def = readValue(ver, 0);
    log->log("value for %d = %d", ver, def);
    return def;
}
开发者ID:mekolat,项目名称:ManaPlus,代码行数:6,代码来源:testmain.cpp


示例15: main

int main(int argc, char *argv[])
{

	char mdesc[2][MAXLEN] = {"#Motordescription (text)",""};
	char pdesc[2][MAXLEN] = {"#Propellerdescription (text)",""};
	char psdesc[2][MAXLEN] = {"#size [in] (eg. 8x4)",""};
	char wbdesc[2][MAXLEN] = {"#weight battery [kg]",""};
	char wrvdesc[2][MAXLEN] = {"#weight receiver + voltmeter [kg]",""};
	char wmspdesc[2][MAXLEN] = {"#weight motor + speedcontroller + propeller [kg]",""};
	char wcdesc[2][MAXLEN] = {"#weight camera [kg]",""};
	char wfdesc[2][MAXLEN] = {"#weight fuselage (center piece) [kg]",""};
	char wadesc[2][MAXLEN] = {"#weight arms [kg]",""};
	char wtdesc[2][MAXLEN] = {"#weight tilt mechanism + servo [kg]",""};
	char again[MAXLEN];
	double bsize;
	double I;
	double m[7];
	double mges;
	int n;
	int nmax;

	if (argc < 2) {
		fprintf(stderr, "Fehlender Dateiname! Aufruf des Programms:\ncopter.exe data.txt\n");
		exit(1);
	}


	readFile(argv[1], mdesc[0], mdesc[1]);

	readFile(argv[1], pdesc[0], pdesc[1]);

	readFile(argv[1], psdesc[0], psdesc[1]);

	readFile(argv[1], wbdesc[0], wbdesc[1]);
	m[0] = readValue(wbdesc[1]);

	readFile(argv[1], wrvdesc[0], wrvdesc[1]);
	m[1] = readValue(wrvdesc[1]);

	readFile(argv[1], wmspdesc[0], wmspdesc[1]);
	m[2] = readValue(wmspdesc[1]);

	readFile(argv[1], wcdesc[0], wcdesc[1]);
	m[3] = readValue(wcdesc[1]);

	readFile(argv[1], wfdesc[0], wfdesc[1]);
	m[4] = readValue(wfdesc[1]);

	readFile(argv[1], wadesc[0], wadesc[1]);
	m[5] = readValue(wadesc[1]);

	readFile(argv[1], wtdesc[0], wtdesc[1]);
	m[6] = readValue(wtdesc[1]);


	while(1) {
		nmax = scanInt("\nMaximale Motorenanzahl: ");
		bsize = scanDouble("Akkukapazitaet [mAh]:");
		printf("\n");		
			printf("Anzahl | I(ges) | m(ges) | Schwebeflugdauer\n");			
			printf("-------------------------------------------\n");
		for ( n = 1; n <= nmax; n++ ) {
			if ( (n % 2) != 0) {

				mges = m[0] + m[1] + n * (m[2] + m[5]) + m[3] + m[4] + 1 * m[6];
			}
			else {

				mges = m[0] + m[1] + n * (m[2] + m[5]) + m[3] + m[4] + 0 * m[6];
			}	

			I = copter_funktion(1,argv[1], mges/n);

			printf("%6d |%6.1lfA |%6.0lfg |\t%5.1lfmin\n", n, I*n,  mges*1000, ((0.8 * (bsize / 1000)) / (I*n) ) * 60 );			
		};

		scanString("\nNochmal? (j/n) : ", again, MAXLEN);
		if (strcasecmp(again, "n") == 0)
			exit(1);
	}

	return 0;
}
开发者ID:Back2RL,项目名称:HelpfulFunctions,代码行数:83,代码来源:copter_v7.c


示例16: readValue

unsigned short PhotoresistorSensor::readValue()
{
	return readValue(true);
}
开发者ID:sn4k3,项目名称:LedClock,代码行数:4,代码来源:PhotoresistorSensor.cpp


示例17: Service_Read

void Service_Read(UA_Server *server, UA_Session *session, const UA_ReadRequest *request,
                  UA_ReadResponse *response) {
    if(request->nodesToReadSize <= 0) {
        response->responseHeader.serviceResult = UA_STATUSCODE_BADNOTHINGTODO;
        return;
    }

    if(request->timestampsToReturn > 3){
    	response->responseHeader.serviceResult = UA_STATUSCODE_BADTIMESTAMPSTORETURNINVALID;
    	return;
    }

    size_t size = request->nodesToReadSize;

    response->results = UA_Array_new(&UA_TYPES[UA_TYPES_DATAVALUE], size);
    if(!response->results) {
        response->responseHeader.serviceResult = UA_STATUSCODE_BADOUTOFMEMORY;
        return;
    }

    response->resultsSize = size;

    if(request->maxAge < 0) {
    	response->responseHeader.serviceResult = UA_STATUSCODE_BADMAXAGEINVALID;
        return;
    }

    /* ### Begin External Namespaces */
    UA_Boolean *isExternal = UA_alloca(sizeof(UA_Boolean) * size);
    UA_memset(isExternal, UA_FALSE, sizeof(UA_Boolean) * size);
    UA_UInt32 *indices = UA_alloca(sizeof(UA_UInt32) * size);
    for(UA_Int32 j = 0;j<server->externalNamespacesSize;j++) {
        size_t indexSize = 0;
        for(size_t i = 0;i < size;i++) {
            if(request->nodesToRead[i].nodeId.namespaceIndex != server->externalNamespaces[j].index)
                continue;
            isExternal[i] = UA_TRUE;
            indices[indexSize] = i;
            indexSize++;
        }
        if(indexSize == 0)
            continue;
        UA_ExternalNodeStore *ens = &server->externalNamespaces[j].externalNodeStore;
        ens->readNodes(ens->ensHandle, &request->requestHeader, request->nodesToRead,
                       indices, indexSize, response->results, UA_FALSE, response->diagnosticInfos);
    }
    /* ### End External Namespaces */

    for(size_t i = 0;i < size;i++) {
        if(!isExternal[i])
            readValue(server, request->timestampsToReturn, &request->nodesToRead[i], &response->results[i]);
    }

#ifdef EXTENSION_STATELESS
    if(session==&anonymousSession){
		/* expiry header */
		UA_ExtensionObject additionalHeader;
		UA_ExtensionObject_init(&additionalHeader);
		additionalHeader.encoding = UA_EXTENSIONOBJECT_ENCODINGMASK_BODYISBYTESTRING;

		UA_Variant variant;
		UA_Variant_init(&variant);
		variant.type = &UA_TYPES[UA_TYPES_DATETIME];
		variant.arrayLength = request->nodesToReadSize;

		UA_DateTime* expireArray = UA_NULL;
		expireArray = UA_Array_new(&UA_TYPES[UA_TYPES_DATETIME], request->nodesToReadSize);
		variant.data = expireArray;

		UA_ByteString str;
		UA_ByteString_init(&str);

		/*expires in 20 seconds*/
		for(UA_Int32 i = 0;i < response->resultsSize;i++) {
			expireArray[i] = UA_DateTime_now() + 20 * 100 * 1000 * 1000;
		}
		size_t offset = 0;
		str.data = UA_malloc(UA_Variant_calcSizeBinary(&variant));
		str.length = UA_Variant_calcSizeBinary(&variant);
		UA_Variant_encodeBinary(&variant, &str, &offset);
		additionalHeader.body = str;
		response->responseHeader.additionalHeader = additionalHeader;
    }
#endif
}
开发者ID:l29ah,项目名称:open62541,代码行数:85,代码来源:ua_services_attribute.c


示例18: readValue

asynStatus daedataDriver::readInt32(asynUser *pasynUser, epicsInt32 *value)
{
	return readValue(pasynUser, "readInt32", value);
}
开发者ID:ISISComputingGroup,项目名称:EPICS-isisdaedata,代码行数:4,代码来源:daedataDriver.cpp


示例19: miniShell

static void miniShell()
{
	static bool inMiniShell = false;
	
	// Stop if the user didn't ask for the minishell
	if (inMiniShell || Serial.available()==0)
	{
		//DbgPrintf("<No commands>");
		return;
	}

	// If the command was not for a shell, exit
	unsigned char cmd = readValue();
	if(cmd != SHELL_REQUESTED)
	{
		DbgPrintf("<error>Unknown command %i</error>", cmd);
		return;
	}
	else
		DbgPrintf("<ret v=\"OK\" />");
	
	inMiniShell = true;

	// Enter the miniShell
	while(true)
	{
		// Get the command
		unsigned char cmd = readValue();
		if(cmd == DIGITAL_READ)
		{
			unsigned char pin = readValue();
			int pin_val = digitalRead(pin);
			const char* ret = (pin_val==HIGH?"HIGH":"LOW");
			DbgPrintf("<ret v=\"%s\"/>", ret);
		}
		else if(cmd == DIGITAL_WRITE)
		{
			unsigned char pin = readValue();
			unsigned char value = readValue();
			digitalWrite(pin, value==1?HIGH:LOW);
			DbgPrintf("<ret v=\"OK\"/>");
		}
		else if(cmd == ANALOG_READ)
		{
			unsigned char pin = readValue();
			int pin_val = analogRead(pin);
			DbgPrintf("<ret v=\"%i\"/>", pin_val);
		}
		else if(cmd == ANALOG_WRITE)
		{
			unsigned char pin = readValue();
			unsigned char value = readValue();
			analogWrite(pin, value);
			DbgPrintf("<ret v=\"OK\"/>");
		}
		else if(cmd == PIN_MODE)
		{
			unsigned char pin = readValue();
			unsigned char mode = readValue();
			pinMode(pin, mode==1?OUTPUT:INPUT);
			DbgPrintf("<ret v=\"OK\"/>");
		}
		else if(cmd == VAR_WRITE)
		{
			DbgSendTrace("Will read string");
			char* frameName=readString();
			char* varName=readString();
			char* value=readString();
			DbgSendTrace("frame=%s, varName=%s, value=%s", frameName, varName, value);
			free(frameName);
			free(varName);
			free(value);
			
			DbgPrintf("<ret v=\"OK\"/>");
		}
		else if(cmd == EXIT_SHELL)
		{
			DbgPrintf("<ret v=\"OK\"/>");
			break;
		}
		else
		{
			DbgPrintf("<error>Unknown command %i</error>", cmd);

			//Empty the input buffer
			while (Serial.available()>0)
				Serial.read();

			// Leave the minishell
			break;
		}
	}
	
	inMiniShell = false;
}
开发者ID:coolshou,项目名称:arduide,代码行数:95,代码来源:IDEdbg.cpp


示例20: parseConfig

int parseConfig(configuration *config)
{
  FILE *configFile;
  char buffert[PATH_MAX], realPathBuff[PATH_MAX];
  char *line = NULL;
  char value[256] = {'\0'};
  size_t  lineIndex = 0, len = sizeof(value);

  sprintf(buffert, "%s/%s", config->rootDir, config->configPath);
  realpath(buffert, realPathBuff);

  if ((configFile = fopen(realPathBuff, "r")) == NULL) {
    printf("CRITICAL: Unable to open config file %s, %s\n", config->accLogPath, strerror(errno));
    return -1;
  }

  while( getline(&line, &len, configFile) != EOF )
  {
    lineIndex = 0;
    // Ignore spaces
    while (line[lineIndex] == ' ')
      lineIndex++;

    // Ignore commented and empty lines
    if( line[lineIndex] != '#' && line[lineIndex] != '\n' )
    {
      // Parse the line
      if (startsWith("Servername", line + lineIndex))
      {
        // Move pass variable name
        lineIndex += strlen("Servername:");

        readValue(lineIndex, line, value, sizeof(value));

        // Check if value is an valid ip address
        if (isValidIpAddress(value))
        {
          strncpy(config->servername,  value, BUF_CFG);
        }
        // Otherwise check if it's an valid domain name and resolve it
        else if(hostnameToIp(value))
        {
          strncpy(config->servername,  value, BUF_CFG);
        }
        // Else this is not a valid config
        else
          printf("Invalid config, hostname\n");

      }
      else if (startsWith("Listen", line + lineIndex))
      {
        int  port = 0;

        // Move pass variable name
        lineIndex += strlen("Listen:");

        readValue(lineIndex, line, value, sizeof(value));

        // Check if valid port number
        if((port = atoi(value)) != 0 && port < 65536)
        {
          config->listenPort = port;
        }
        // Else invalid
        else
        {
          printf("Invalid config, port\n");
        }
      }
      else if (startsWith("Basedir", line + lineIndex))
      {
        // Move pass variable name
        lineIndex += strlen("Basedir:");

        readValue(lineIndex, line, value, sizeof(value));

        // relative the root dir
        sprintf(buffert, "%s/%s", config->rootDir, value);

        // Get the realpath
        if(realpath(buffert, realPathBuff) == NULL){
          printf("Invalid config, basedirectory: %s, %s\n", realPathBuff, strerror(errno));
          exit(-1);
        }

        // Change basedirectory to the realpath
        strncpy(config->basedir, realPathBuff, BUF_CFG);
      }
      else if (startsWith("Method", line + lineIndex))
      {
        // Move pass variable name
        lineIndex += strlen("Method:");

        readValue(lineIndex, line, value, sizeof(value));

        // If selected logging method is to a file
        if((strcmp(value, "file")) == 0)
        {
          config->syslog = false;

//.........这里部分代码省略.........
开发者ID:K1N62,项目名称:Rhino,代码行数:101,代码来源:config.c



注:本文中的readValue函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ readWord函数代码示例发布时间:2022-05-30
下一篇:
C++ readUint32函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap