bool disconnectFromAP(){ int x; Serial1.println("AT+CWQAP"); Serial1.flush(); String response = Serial1.readStringUntil(Serial1.available()); if(response.length() > 2){ x = findString("OK", response); } else{ SerialUSB.println("Wi-Fi Disconnection Timeout!"); return false; } if(x != -1){ SerialUSB.println("Wi-Fi Disconnected from AP"); return true; } else{ SerialUSB.println("Wi-Fi Couldn't Disconnect from AP!"); return false; } }
/* * Search for a line which contains the specified string. * If the string is NULL, then the previously searched for string * is used. The currently searched for string is saved for future use. * Returns the line number which matches, or 0 if there was no match * with an error printed. */ static int searchLines(const char *str, int num1, int num2) { const LINE *lp; int len; if ((num1 < 1) || (num2 > lastNum) || (num1 > num2)) { bb_error_msg("bad line numbers for search"); return 0; } if (*str == '\0') { if (searchString[0] == '\0') { bb_error_msg("no previous search string"); return 0; } str = searchString; } if (str != searchString) strcpy(searchString, str); len = strlen(str); lp = findLine(num1); if (lp == NULL) return 0; while (num1 <= num2) { if (findString(lp, str, len, 0) >= 0) return num1; num1++; lp = lp->next; } bb_error_msg("cannot find string \"%s\"", str); return 0; }
bool sleep(int time){ int x; Serial1.println("AT+GSLP="+String(time)); Serial1.flush(); String response = Serial1.readStringUntil(Serial1.available()); if(response.length() > 2){ x = findString("OK", response); } else{ SerialUSB.println("Wi-Fi Sleeping Timeout!"); return false; } if(x != -1){ SerialUSB.println("Wi-Fi went to Deep Sleep"); return true; } else{ SerialUSB.println("Wi-Fi couldn't Seep Sleep!"); return false; } }
bool setWifiTransmissionMode(){ int x; Serial1.println("AT+CIPMODE=0"); Serial1.flush(); String response = Serial1.readStringUntil(Serial1.available()); if(response.length() > 2){ x = findString("OK", response); } else{ SerialUSB.println("Wi-Fi Transmission Mode Timeout!"); return false; } if(x != -1){ SerialUSB.println("Wi-Fi Transmission Mode Set"); return true; } else{ SerialUSB.println("Couldn't set Wi-Fi Transmission Mode!"); return false; } }
bool closeConnection(){ int x; Serial1.println("AT+CIPCLOSE"); Serial1.flush(); String response = Serial1.readStringUntil(Serial1.available()); if(response.length() > 2){ x = findString("OK", response); } else{ SerialUSB.println("Wi-Fi Server Connection Closing Timeout!"); return false; } if(x != -1){ SerialUSB.println("Wi-Fi Server Connection Closed"); return true; } else{ SerialUSB.println("Wi-Fi Server Connection Can't be Closed!"); return false; } }
int main (void) { int index; int findString (const char source[], const char s[]); const char src[20]; const char find[10]; printf("Enter the source string \n"); scanf("%s", &src); printf("Enter the text to be found \n"); scanf("%s", &find); index = findString(src, find); //if(index == 1 ) printf("%s is found in %i position of %s", find,index, src); //else // printf("%s is not found in %s", find, src); return 0; }
bool sendDataLength(String tcpHeader, String path, String servername, String data){ int x; Serial1.print("AT+CIPSEND="); Serial1.println(tcpHeader.length()+data.length()+4); Serial1.flush(); String response = Serial1.readStringUntil(Serial1.available()); if(response.length() > 2){ x = findString(">", response); } else{ SerialUSB.println("Wi-Fi Sending data length Timeout!"); return false; } if(x != -1){ SerialUSB.println("Wi-Fi ready to send data"); return true; } else{ SerialUSB.println("Wi-Fi is not ready to send data, Issue with the link!"); return false; } }
Pywrap::Pywrap(const char* file, unsigned int arg_size) { if(file != "") { if(findString(".py",file)>= 0) { file = sliceStr(file,0,std::string(file).size() - 3).c_str(); } SetFilePath(file); name_space = PyString_FromString(file); module = PyImport_Import(name_space); PyErr_Print();//get error output if import fails :). Py_DECREF(name_space); fileLoaded = true; } else { fileLoaded = false; } args = PyTuple_New(arg_size); sizeT = arg_size; index = 0; }
bool moduleResponds(){ int x; Serial1.println("AT"); Serial1.flush(); String response = Serial1.readStringUntil(Serial1.available()); if(response.length() > 2){ x = findString("OK", response); } else{ SerialUSB.println("Wi-Fi Module respond Timeout!"); return false; } if(x != -1){ SerialUSB.println("Wi-Fi Module responds"); return true; } else{ SerialUSB.println("Wi-Fi Module doesn't respond!"); return false; } }
void send_to_eventlog (short evt_num, short EventLogType, char *ComponentName, char *ObjectRef, short nToken, va_list marker) { BOOL found = FALSE; short i,j; int err, tokIdLen, idx; char sqleventBuf[MAX_EVT_BUF_SIZE]; char *TokenPtr; char tmpBuf[MS_MON_MAX_PROCESS_NAME + 64]; size_t szBuf = MAX_EVT_BUF_SIZE; logLevel severity; sqleventBuf[0] = '\0'; string logMsg; logMsg.reserve(MAX_EVT_BUF_SIZE); static char process_name[MS_MON_MAX_PROCESS_NAME]; static int nid, pid; if (process_name[0] == 0) { msg_mon_get_my_process_name(process_name ,MS_MON_MAX_PROCESS_NAME ); msg_mon_get_process_info(process_name, &nid, &pid); } for (i = 0, found = FALSE; eventDataMap[i].eventId != 0L ; i++) { if (eventDataMap[i].eventId == evt_num) { found = TRUE; //sprintf(tmpBuf, "%.30s (%d,%d): %ld ",process_name, nid, pid, getLongEventId(1, SQEVL_NDCS, evt_num, 9)); sprintf(tmpBuf, "Node Number: %d, CPU: %d, PIN:%ld, Process Name:%.30s , , ,", nid, nid, pid, process_name); logMsg.append(tmpBuf); for (j=0;eventDataMap[i].msgPtr[j] !=NULL || j>6 ;j++ ) { logMsg.append(eventDataMap[i].msgPtr[j]); } break; } } if (!found) { stringstream ss("ODBCMXEventMsg::send_to_eventlog: eventDataMap entry not found "); throw(ss.str()) ; } _itoa(EventLogType, tmpBuf, 10); // if (findString("<1>",&idx, logMsg)) // logMsg.replace( logMsg.find("<1>"), 3, tmpBuf ); // if (findString("<2>",&idx, logMsg)) // logMsg.replace( logMsg.find("<2>"), 3, ComponentName ); // if (findString("<3>",&idx, logMsg)) // logMsg.replace( logMsg.find("<3>"), 3, ObjectRef ); for ( i=0,j=4; i<nToken; i++,j++ ) { TokenPtr = va_arg(marker, char *); //errno = strstr(TokenPtr, "4126"); tokIdLen = sprintf(tmpBuf,"<%d>",j); if (!findString(tmpBuf,&idx, logMsg)) logMsg.append( TokenPtr ); else logMsg.replace( idx, tokIdLen, TokenPtr ); } va_end(marker); const char *logMsgStr = logMsg.c_str(); switch (EventLogType) { case EVENTLOG_ERROR_TYPE: severity = LL_ERROR; break; case EVENTLOG_WARNING_TYPE: severity = LL_WARN; break; case EVENTLOG_INFORMATION_TYPE: severity = LL_INFO; break; default: severity = LL_ERROR; } CommonLogger::log(MXOSRVR_COMPONENT, severity, logMsgStr); }
void processMeme(FILE* infile, struct meme* myMeme, struct act* myAct, struct font* myFont){ char cur = fgetc(infile); char* current = (char*) calloc(50, sizeof(char)); int i = 0, k = 0, temp = 0; int font = 0, meme = 0, memeImage = 0; int* numTextIDs = (int*) calloc(myAct->numTextIDs, sizeof(int)); while ( cur != EOF ) { current[i] = cur; /* Check if action file meme is in meme file */ if ( strcmp(current,"MEMES") == 0 ) { if ( !findString(infile,myAct->meme) ) { printf("Could not find designated meme in meme file.\n"); exit(0); } free(current); current = (char*) calloc(50, sizeof(char)); i = -1; meme = 1; } /* Find our font file */ if ( strcmp(current,"FONTS") == 0 ) { free(current); findStringOpenFont(infile, myAct->font, myFont); /* current = strcat(myAct->font, ".fsf"); if ( !findString(infile,current) ) { printf("Could not find designated font in meme file.\n"); exit(0); } myAct->font = (char*) calloc(49, sizeof(char)); strcpy(myAct->font, current); free(current); */ current = (char*) calloc(50, sizeof(char)); i = -1; font = 1; } /* Check the meme identifiers*/ if ( strcmp(current, myAct->meme) == 0 && meme) { temp = checkAndStoreID(infile, myAct, myMeme); /* printf("Happened. Temp = %d\n", temp); */ if ( temp == 1) { numTextIDs[k] = 1; k++; } else if ( temp == 2 ) { memeImage = 1; } free(current); current = (char*) calloc(50, sizeof(char)); i = -1; temp = 0; } if ( cur == '\n' || cur == ((char) 13) ) { free(current); current = (char*) calloc(50, sizeof(char)); i = -1; } cur = fgetc(infile); i++; } if ( !meme ) { printf("Couldn't find MEMES tag.\n"); exit(0); } else if ( !memeImage ) { printf("Couldn't find our meme's image file tag!\n"); exit(0); } else if ( !font ) { printf("Couldn't find the fonts tag!\n"); exit(0); } for ( i = 0; i < myAct->numTextIDs; i ++ ) { if ( numTextIDs[i] != 1 ) { printf("For some reason we couldn't find the information for all of the text id's specified in the act file\n"); exit(0); } } free(current); free(numTextIDs); }
void CCommandLine::Execute() { if (m_nOperationType == FIND_AVAILABLE_TRACE_ID) { std::map<tstring, int> alreadyUsed; std::vector<tstring> availableTraces; CTools::FindAvailableTraces(m_strSourcePath, m_strTraceID, alreadyUsed, availableTraces, FALSE); //Export the result to file Poco::FileOutputStream fileStream(m_strExportFileName); if (fileStream.good()) { //Write already used trace IDs fileStream << "Trace Header: '" << m_strTraceHeader << "'"<< "\n"; fileStream << "Already Used Trace IDs:" << "\n"; std::map<tstring, int>::iterator ite = alreadyUsed.begin(); char buff[32]; while (ite != alreadyUsed.end()) { fileStream << " " << ite->first << ":" << itoa(ite->second, buff, 10) << "\n"; ++ite; } fileStream << "Available Trace IDs:" << "\n"; for (int i = 0; i < availableTraces.size(); ++i) { fileStream << " " << availableTraces.at(i) << "\n"; ++ite; } fileStream.close(); } } else if (m_nOperationType == FIND_TRACE_ID) { std::map<tstring, int> traceIDMap; CTools::FindASpecTraceID(m_strSourcePath, m_strTraceID, traceIDMap, FALSE); //Export the result to file Poco::FileOutputStream fileStream(m_strExportFileName); char buff[32]; if (fileStream.good()) { //Write already used trace IDs fileStream << "Trace ID '" << m_strTraceID << "'"<< "\n"; std::map<tstring, int>::iterator ite = traceIDMap.begin(); while (ite != traceIDMap.end()) { fileStream << " " << ite->first << ":" << itoa(ite->second, buff, 10) << "\n"; ++ite; } fileStream.close(); } } else if (m_nOperationType == FIND_UNUSED_TRACE_ID) { try { XMLParser parser; parser.StartXML(m_strMessageFile); std::map<tstring, tstring> messageIDMap; const std::vector<tstring>& msgIDs = parser.getMessageIDs(); if (msgIDs.size() > 0) { //Remove the odd IDs messageIDMap.clear(); std::vector<tstring> filters; std::vector<tstring> files; filters.push_back(CPPSOURCEFILE); try { m_strSourcePath = CTools::ReplaceEnvVar(m_strSourcePath); CTools::IteratorDir(m_strSourcePath, filters, files); } catch (const std::exception& e) { CTraceLogger::getLogger().information(tstring("CCommandLine::Execute() - Exception when iterate dir") + e.what()); return; } for (int i = 0; i < files.size(); ++i) { CFindStringInFile findString(files.at(i)); for (int j = 0; j < msgIDs.size(); ++j) { if (messageIDMap.find(msgIDs.at(j)) == messageIDMap.end()) { if (findString.FindString(msgIDs.at(j))) messageIDMap[msgIDs.at(j)] = files.at(i); } } } if (messageIDMap.size() > 0) { //Export the result to file Poco::FileOutputStream fileStream(m_strExportFileName); if (fileStream.good()) { //Write already used trace IDs std::map<tstring, tstring>::iterator ite = messageIDMap.begin(); while (ite != messageIDMap.end()) { fileStream << ite->first << " : " << ite->second << "\n"; ++ite; } fileStream.close(); } } } } catch (const std::exception& e) { CTraceLogger::getLogger().information(tstring("CCommandLine::Execute() - Exception when execute operation 'FIND_UNUSED_TRACE_ID'") + e.what()); } } }
/// Make wxPdfDocument font metrics file based on AFM file bool MakeFont::MakeFontAFM(const wxString& fontFileName, const wxString& afmFileName, const wxString& encoding, const wxString& type, const wxString& patch) { bool valid = false; wxString fontType = type; wxFileName fileName(fontFileName); // Find font type if (fontFileName.Length() > 0) { wxString ext = fileName.GetExt(); if (ext == wxT("ttf")) { fontType = wxT("TrueType"); } else if (ext == wxT("pfb")) { fontType = wxT("Type1"); } else { wxLogMessage(wxT("Warning: Unrecognized font file extension (") + ext + wxT("), ") + fontType + wxT(" font assumed.")); } } bool embeddingAllowed = true; bool subsettingAllowed = true; if (fontFileName.Length() > 0) { int cffOffset, cffLength; if (fontType == wxT("TrueType")) { CheckTTF(fontFileName, embeddingAllowed, subsettingAllowed, cffOffset, cffLength); } } wxPdfFontData* afmFont; if (fontType == wxT("TrueType")) { afmFont = new wxPdfFontDataTrueType(); } else { afmFont = new wxPdfFontDataType1(); } // Initialize font description wxPdfFontDescription fd; fd.SetAscent(1000); fd.SetDescent(-200); fd.SetItalicAngle(0); fd.SetStemV(70); fd.SetMissingWidth(600); fd.SetUnderlinePosition(-100); fd.SetUnderlineThickness(50); bool hasCapHeight = false; bool hasXCapHeight = false; bool hasXHeight = false; bool hasFontBBox = false; bool hasStemV = false; bool hasMissingWidth = false; int flags = 0; CTGMap cc2gn; CTGMap cc2gnPatch; if (encoding.Length() > 0) { afmFont->SetEncoding(encoding); valid = ReadMap(encoding, cc2gn); if (!valid) { delete afmFont; return false; } if (patch.Length() > 0) { valid = ReadMap(patch, cc2gnPatch); if (valid) { CTGMap::iterator patchIter; for (patchIter = cc2gnPatch.begin(); patchIter != cc2gnPatch.end(); patchIter++) { cc2gn[patchIter->first] = patchIter->second; } } else { wxLogMessage(wxT("Warning: Unable to read patch file '") + patch + wxT("'.")); } } } // Read a font metric file wxFileInputStream afmFile(afmFileName); if (!afmFile.Ok()) { wxLogMessage(wxT("Error: Unable to read AFM file '") + afmFileName + wxT("'.")); delete afmFont; return false; } wxTextInputStream text(afmFile); FixGlyphMap fix; fix[wxT("Edot")] = wxT("Edotaccent"); fix[wxT("edot")] = wxT("edotaccent"); fix[wxT("Idot")] = wxT("Idotaccent"); fix[wxT("Zdot")] = wxT("Zdotaccent"); fix[wxT("zdot")] = wxT("zdotaccent"); fix[wxT("Odblacute")] = wxT("Ohungarumlaut"); fix[wxT("odblacute")] = wxT("ohungarumlaut"); fix[wxT("Udblacute")] = wxT("Uhungarumlaut"); fix[wxT("udblacute")] = wxT("uhungarumlaut"); fix[wxT("Gcedilla")] = wxT("Gcommaaccent"); fix[wxT("gcedilla")] = wxT("gcommaaccent"); fix[wxT("Kcedilla")] = wxT("Kcommaaccent"); fix[wxT("kcedilla")] = wxT("kcommaaccent"); fix[wxT("Lcedilla")] = wxT("Lcommaaccent"); fix[wxT("lcedilla")] = wxT("lcommaaccent"); fix[wxT("Ncedilla")] = wxT("Ncommaaccent"); fix[wxT("ncedilla")] = wxT("ncommaaccent"); fix[wxT("Rcedilla")] = wxT("Rcommaaccent"); fix[wxT("rcedilla")] = wxT("rcommaaccent"); fix[wxT("Scedilla")] = wxT("Scommaaccent"); fix[wxT("scedilla")] = wxT("scommaaccent"); fix[wxT("Tcedilla")] = wxT("Tcommaaccent"); fix[wxT("tcedilla")] = wxT("tcommaaccent"); fix[wxT("Dslash")] = wxT("Dcroat"); fix[wxT("dslash")] = wxT("dcroat"); fix[wxT("Dmacron")] = wxT("Dcroat"); fix[wxT("dmacron")] = wxT("dcroat"); fix[wxT("combininggraveaccent")] = wxT("gravecomb"); fix[wxT("combininghookabove")] = wxT("hookabovecomb"); fix[wxT("combiningtildeaccent")] = wxT("tildecomb"); fix[wxT("combiningacuteaccent")] = wxT("acutecomb"); fix[wxT("combiningdotbelow")] = wxT("dotbelowcomb"); fix[wxT("dongsign")] = wxT("dong"); // Read the AFM font metric file wxPdfGlyphWidthMap* widths = new wxPdfGlyphWidthMap(); wxPdfChar2GlyphMap* glyphs = new wxPdfChar2GlyphMap(); long cc; if (!cc2gn.empty()) { for (cc = 0; cc <= 255; cc++) { (*widths)[cc] = 0xFFFF; (*glyphs)[cc] = 0; } } wxString line; wxString charcode, glyphname; wxString code, param, dummy, glyph; wxString token, tokenBoxHeight; long nParam, incWidth = -1, incGlyph = 0; long width, boxHeight, glyphNumber; wxString weight; bool hasGlyphNumbers = false; while (!afmFile.Eof()) { line = text.ReadLine(); line.Trim(); wxStringTokenizer tkz(line, wxT(" ")); int count = (int) tkz.CountTokens(); if (count < 2) continue; code = tkz.GetNextToken(); // 0 param = tkz.GetNextToken(); // 1 if (code == wxT("C")) { width = -1; glyphNumber = 0; boxHeight = 0; tokenBoxHeight = wxEmptyString; // Character metrics param.ToLong(&cc); dummy = tkz.GetNextToken(); // 2 while (tkz.HasMoreTokens()) { token = tkz.GetNextToken(); if (token == wxT("WX")) // Character width { param = tkz.GetNextToken(); // Width param.ToLong(&width); dummy = tkz.GetNextToken(); // Semicolon } else if (token == wxT("N")) // Glyph name { glyphname = tkz.GetNextToken(); // Glyph name dummy = tkz.GetNextToken(); // Semicolon } else if (token == wxT("G")) // Glyph number { hasGlyphNumbers = true; param = tkz.GetNextToken(); // Number param.ToLong(&glyphNumber); dummy = tkz.GetNextToken(); // Semicolon } else if (token == wxT("B")) // Character bounding box { dummy = tkz.GetNextToken(); // x left dummy = tkz.GetNextToken(); // y bottom dummy = tkz.GetNextToken(); // x right tokenBoxHeight = tkz.GetNextToken(); // y top tokenBoxHeight.ToLong(&boxHeight); dummy = tkz.GetNextToken(); // Semicolon } else { while (tkz.HasMoreTokens() && tkz.GetNextToken() != wxT(";")); } } if (glyphname.Right(4) == wxT("20AC")) { glyphname = wxT("Euro"); } if (glyphname == wxT("increment")) { incWidth = width; if (hasGlyphNumbers) { incGlyph = glyphNumber; } } if (fix.find(glyphname) != fix.end()) { //Fix incorrect glyph name for (int i = 0; i <= 255; i++) { if (cc2gn[i] == fix[glyphname]) { cc2gn[i] = glyphname; } } } if (cc2gn.empty()) { // Symbolic font: use built-in encoding (*widths)[cc] = width; if (hasGlyphNumbers) { (*glyphs)[cc] = glyphNumber; } if (!hasCapHeight && !hasXCapHeight && cc == 'X' && tokenBoxHeight != wxEmptyString) { hasXCapHeight = true; fd.SetCapHeight(boxHeight); } if (!hasXHeight && cc == 'x' && tokenBoxHeight != wxEmptyString) { hasXHeight = true; fd.SetXHeight(boxHeight); } } else { // Search glyphname in cc2gn bool found = false; for (int i = 0; i <= 255; i++) { if (cc2gn[i] == glyphname) { found = true; (*widths)[i] = width; if (hasGlyphNumbers) { (*glyphs)[i] = glyphNumber; } } } if (!found) { wxLogMessage(wxT("Warning: character '") + glyphname + wxT("' is undefined.")); } if (!hasCapHeight && !hasXCapHeight && glyphname == wxT("X") && tokenBoxHeight != wxEmptyString) { hasXCapHeight = true; fd.SetCapHeight(boxHeight); } if (!hasXHeight && glyphname == wxT("x") && tokenBoxHeight != wxEmptyString) { hasXHeight = true; fd.SetXHeight(boxHeight); } } if (!hasMissingWidth && glyphname == wxT(".notdef")) { hasMissingWidth = true; fd.SetMissingWidth(width); } } else if (code == wxT("FontName")) { afmFont->SetName(param); } else if (code == wxT("Weight")) { wxString weight = param.Lower(); if (!hasStemV && (weight == wxT("black") || weight == wxT("bold"))) { fd.SetStemV(120); } } else if (code == wxT("ItalicAngle")) { double italic; param.ToDouble(&italic); int italicAngle = int(italic); fd.SetItalicAngle(italicAngle); if (italicAngle > 0) { flags += 1 << 6; } } else if (code == wxT("Ascender")) { long ascent; param.ToLong(&ascent); fd.SetAscent(ascent); } else if (code == wxT("Descender")) { param.ToLong(&nParam); fd.SetDescent(nParam); } else if (code == wxT("UnderlineThickness")) { param.ToLong(&nParam); fd.SetUnderlineThickness(nParam); } else if (code == wxT("UnderlinePosition")) { param.ToLong(&nParam); fd.SetUnderlinePosition(nParam); } else if (code == wxT("IsFixedPitch")) { if (param == wxT("true")) { flags += 1 << 0; } } else if (code == wxT("FontBBox")) { hasFontBBox = true; wxString bbox2 = tkz.GetNextToken(); wxString bbox3 = tkz.GetNextToken(); wxString bbox4 = tkz.GetNextToken(); wxString bBox = wxT("[") + param + wxT(" ") + bbox2 + wxT(" ") + bbox3 + wxT(" ") + bbox4 + wxT("]"); fd.SetFontBBox(bBox); } else if (code == wxT("CapHeight")) { hasCapHeight = true; long capHeight; param.ToLong(&capHeight); fd.SetCapHeight(capHeight); } else if (code == wxT("StdVW")) { hasStemV = true; long stemV; param.ToLong(&stemV); fd.SetStemV(stemV); } } for (cc = 0; cc <= 255; cc++) { if ((*widths)[cc] == 0xFFFF) { if (cc2gn[cc] == wxT("Delta") && incWidth >= 0) { (*widths)[cc] = incWidth; if (hasGlyphNumbers) { (*glyphs)[cc] = incGlyph; } } else { (*widths)[cc] = fd.GetMissingWidth(); if (hasGlyphNumbers) { (*glyphs)[cc] = 0; } wxLogMessage(wxT("Warning: character '") + cc2gn[cc] + wxT("' is missing.")); } } } wxString diffs; if (encoding.Length() > 0) { // Build differences from reference encoding CTGMap cc2gnRef; valid = ReadMap(wxT("cp1252"), cc2gnRef); diffs = wxT(""); int last = 0; for (int i = 32; i <= 255; i++) { if (cc2gn[i] != cc2gnRef[i]) { if (i != last+1) { diffs += wxString::Format(wxT("%d "), i); } last = i; diffs = diffs + wxT("/") + cc2gn[i] + wxT(" "); } } } afmFont->SetDiffs(diffs); if (cc2gn.empty()) { flags += 1 << 2; } else { flags += 1 << 5; } fd.SetFlags(flags); if (!hasCapHeight && !hasXCapHeight) { fd.SetCapHeight(fd.GetAscent()); } if (!hasFontBBox) { wxString fbb = wxString::Format(wxT("[0 %d 1000 %d]"), fd.GetDescent()-100, fd.GetAscent()+100); fd.SetFontBBox(fbb); } afmFont->SetGlyphWidthMap(widths); afmFont->SetChar2GlyphMap(glyphs); afmFont->SetDescription(fd); wxString baseName = fileName.GetName(); if (embeddingAllowed) { if (fontType == wxT("TrueType")) { wxFileInputStream ttfFile(fontFileName); if (!ttfFile.Ok()) { wxLogMessage(wxT("Error: Unable to read font file '") + fontFileName + wxT("'.")); delete afmFont; return false; } size_t len = ttfFile.GetLength(); wxFileOutputStream outFontFile(baseName + wxT(".z")); wxZlibOutputStream zOutFontFile(outFontFile); zOutFontFile.Write(ttfFile); zOutFontFile.Close(); afmFont->SetFontFile(baseName + wxT(".z")); afmFont->SetSize1(len); wxLogMessage(wxT("Font file compressed (") + baseName + wxT(".z).")); } else { wxFileInputStream pfbFile(fontFileName); if (!pfbFile.Ok()) { wxLogMessage(wxT("Error: Unable to read font file '") + fontFileName + wxT("'.")); delete afmFont; return false; } size_t len = pfbFile.GetLength(); // Find first two sections and discard third one unsigned char* buffer = new unsigned char[len]; unsigned char* buf1 = buffer; unsigned char* buf2; pfbFile.Read(buffer, len); unsigned char first = buffer[0]; if (first == 128) { // Strip first binary header buf1 += 6; len -= 6; } int* f = makeFail("eexec",5); int size1 = (int) findString((char*) buf1, len, "eexec", 5, f); delete [] f; int size2 = -1; if (size1 >= 0) { size1 += 6; unsigned char second = buf1[size1]; buf2 = buf1 + size1; len -= size1; if (first == 128 && second == 128) { // Strip second binary header buf2 += 6; len -= 6; } f = makeFail("00000000",8); size2 = (int) findString((char*) buf2, len, "00000000", 8, f); delete [] f; if (size2 >= 0) { wxFileOutputStream outFontFile(baseName + wxT(".z")); wxZlibOutputStream zOutFontFile(outFontFile); zOutFontFile.Write(buf1, size1); zOutFontFile.Write(buf2, size2); afmFont->SetFontFile(baseName + wxT(".z")); afmFont->SetSize1(size1); afmFont->SetSize2(size2); } } delete [] buffer; if (size1 < 0 || size2 < 0) { wxLogMessage(wxT("Warning: Font file does not seem to be valid Type1, font embedding not possible.")); } } } else { if (fontFileName.Length() > 0) { wxLogMessage(wxT("Warning: Font license does not allow embedding.")); } else { wxLogMessage(wxT("Warning: Font file name missing, font embedding not possible.")); } } // Create XML file CreateFontMetricsFile(baseName + wxT(".xml"), *afmFont, hasGlyphNumbers); wxLogMessage(wxT("Font definition file generated (") + baseName + wxT(".xml).")); //delete widths; delete afmFont; return true; }
char replc[10]; printf("the source string is = %s \n",src); replaceString(src, "bca", "mca", index); return 0; } int replaceString( char source[], char s1[], char s2[], int index ) { char final[20]; int findString (char source[], char s1[]); char remov( char source[], char s1[], char s2[], int index); index = findString (source, s1); //printf("It is found in %i position",index); remov(source, s1, s2, index); } int findString (char source[], char s1[]) { int i; int j; bool found = false; for ( i = 0; source[i] != '\0' && !found; ++i ) { found = true;
/* * Do the substitute command. * The current line is set to the last substitution done. */ static void subCommand(const char * cmd, NUM num1, NUM num2) { int delim; char * cp; char * oldStr; char * newStr; LEN oldLen; LEN newLen; LEN deltaLen; LEN offset; LINE * lp; LINE * nlp; BOOL globalFlag; BOOL printFlag; BOOL didSub; BOOL needPrint; char buf[USERSIZE]; if ((num1 < 1) || (num2 > lastNum) || (num1 > num2)) { fprintf(stderr, "Bad line range for substitute\n"); return; } globalFlag = FALSE; printFlag = FALSE; didSub = FALSE; needPrint = FALSE; /* * Copy the command so we can modify it. */ strcpy(buf, cmd); cp = buf; if (isBlank(*cp) || (*cp == '\0')) { fprintf(stderr, "Bad delimiter for substitute\n"); return; } delim = *cp++; oldStr = cp; cp = strchr(cp, delim); if (cp == NULL) { fprintf(stderr, "Missing 2nd delimiter for substitute\n"); return; } *cp++ = '\0'; newStr = cp; cp = strchr(cp, delim); if (cp) *cp++ = '\0'; else cp = ""; while (*cp) switch (*cp++) { case 'g': globalFlag = TRUE; break; case 'p': printFlag = TRUE; break; default: fprintf(stderr, "Unknown option for substitute\n"); return; } if (*oldStr == '\0') { if (searchString[0] == '\0') { fprintf(stderr, "No previous search string\n"); return; } oldStr = searchString; } if (oldStr != searchString) strcpy(searchString, oldStr); lp = findLine(num1); if (lp == NULL) return; oldLen = strlen(oldStr); newLen = strlen(newStr); deltaLen = newLen - oldLen; offset = 0; nlp = NULL; while (num1 <= num2) { offset = findString(lp, oldStr, oldLen, offset); if (offset < 0) { if (needPrint) { printLines(num1, num1, FALSE); needPrint = FALSE; } offset = 0; lp = lp->next; num1++; continue; } needPrint = printFlag; didSub = TRUE; dirty = TRUE; /* * If the replacement string is the same size or shorter * than the old string, then the substitution is easy. */ if (deltaLen <= 0) { memcpy(&lp->data[offset], newStr, newLen); if (deltaLen) { memcpy(&lp->data[offset + newLen], &lp->data[offset + oldLen], lp->len - offset - oldLen); lp->len += deltaLen; } offset += newLen; if (globalFlag) continue; if (needPrint) { printLines(num1, num1, FALSE); needPrint = FALSE; } lp = lp->next; num1++; continue; } /* * The new string is larger, so allocate a new line * structure and use that. Link it in in place of * the old line structure. */ nlp = (LINE *) malloc(sizeof(LINE) + lp->len + deltaLen); if (nlp == NULL) { fprintf(stderr, "Cannot get memory for line\n"); return; } nlp->len = lp->len + deltaLen; memcpy(nlp->data, lp->data, offset); memcpy(&nlp->data[offset], newStr, newLen); memcpy(&nlp->data[offset + newLen], &lp->data[offset + oldLen], lp->len - offset - oldLen); nlp->next = lp->next; nlp->prev = lp->prev; nlp->prev->next = nlp; nlp->next->prev = nlp; if (curLine == lp) curLine = nlp; free(lp); lp = nlp; offset += newLen; if (globalFlag) continue; if (needPrint) { printLines(num1, num1, FALSE); needPrint = FALSE; } lp = lp->next; num1++; } if (!didSub) fprintf(stderr, "No substitutions found for \"%s\"\n", oldStr); }
static AGArray * getUserInfo() { AGArray * result = NULL; HANDLE hFile; HANDLE hMapping; char usersFile[MAX_PATH]; char *userData; char *current; char *maxData; int fileSize; char *name, *dir; usersFile[0] = '\0'; getUsersFile(usersFile, MAX_PATH); hFile = CreateFile(usersFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) return NULL; fileSize = GetFileSize(hFile, NULL); hMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL); if (NULL != hMapping) { userData = (char *)MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0); maxData = userData + fileSize; result = AGArrayNew(AGUnownedPointerElements, 0); if (NULL != result) { for (current = userData; current < maxData; current++) { if ((name = findString(current, maxData)) && (dir = findString(current + strlen(name) + 1, maxData))) { AGUserInfo * user; int id; id = findID(current - 4); user = (AGUserInfo *)malloc(sizeof(AGUserInfo)); if (NULL != user) { user->name = name; user->dir = dir; user->id = id; current += strlen(name) + strlen(dir) + 1; AGArrayAppend(result, user); } } } } UnmapViewOfFile(userData); CloseHandle(hMapping); } CloseHandle(hFile); return result; }
const char * Auth::getPassword() { return findString(AUTH_PASSWORD); }
void CHZDLReport::GetData(string deviceName, string & sIP, bool & useCPU, bool & useMemory, float & CPUUtl, float & MemoryUtl) { list<string> getMonList; list<string>::iterator getMonItem; string MonitorID; OBJECT tmpObjMonitor = NULL; OBJECT tmpObjTempMonitor = NULL; MAPNODE tmpMonitorNode = NULL; MAPNODE tmpMonitorTempNode = NULL; MAPNODE tempParamNode = NULL; LISTITEM ParamItem; bool bFind; string tmpMonitorTempName; useCPU = false; useMemory = false; CPUUtl = 0; MemoryUtl = 0; bFind = GetSubMonitorsIDByEntity(GetEntity(deviceName), getMonList); if (!bFind) return; MAPNODE tmpEntityNode = NULL; tmpEntityNode = GetEntityMainAttribNode(GetEntity(deviceName)); string v; bFind = FindNodeValue(tmpEntityNode, "_MachineName", v); if (bFind) { sIP = v; } getMonItem = getMonList.begin(); while ( (getMonItem != getMonList.end()) && ( (!useCPU) || (!useMemory) ) ) { MonitorID = *getMonItem; tmpObjMonitor = GetMonitor(MonitorID); if (tmpObjMonitor != INVALID_VALUE) { tmpMonitorNode = GetMonitorMainAttribNode(tmpObjMonitor); string TypeID; bFind = FindNodeValue(tmpMonitorNode, "sv_monitortype", TypeID); int iType = atoi(TypeID.c_str()); tmpObjTempMonitor = GetMonitorTemplet(iType); if(tmpObjTempMonitor!=INVALID_VALUE) { tmpMonitorTempNode = GetMTMainAttribNode(tmpObjTempMonitor); bFind = FindNodeValue(tmpMonitorTempNode, "sv_name", tmpMonitorTempName); if (!useCPU) { string stmp1 = "CPU"; string stmp2 = "Cpu"; string stmp3 = "cpu"; if ( findString(tmpMonitorTempName, stmp1) || findString(tmpMonitorTempName, stmp2) || findString(tmpMonitorTempName, stmp3) ) { bFind = FindMTReturnFirst(tmpObjTempMonitor, ParamItem); bool findPrimary = false; while( ((tempParamNode=::FindNext(ParamItem)) != INVALID_VALUE) && !findPrimary ) { string szPrimary; FindNodeValue(tempParamNode, "sv_primary",szPrimary); if(strcmp(szPrimary.c_str(), "1") == 0) { findPrimary = true; string tmpFieldName; FindNodeValue(tempParamNode, "sv_name", tmpFieldName); CPUUtl = CalcAverage(MonitorID, tmpFieldName); } } useCPU = true; } } if (!useMemory) { string stmp = "Memory"; if ( findString(tmpMonitorTempName, stmp) ) { bFind = FindMTReturnFirst(tmpObjTempMonitor, ParamItem); bool findPrimary = false; while( ((tempParamNode=::FindNext(ParamItem)) != INVALID_VALUE) && !findPrimary ) { string szPrimary; FindNodeValue(tempParamNode, "sv_primary",szPrimary); if(strcmp(szPrimary.c_str(), "1") == 0) { findPrimary = true; string tmpFieldName; FindNodeValue(tempParamNode, "sv_name", tmpFieldName); MemoryUtl = CalcAverage(MonitorID, tmpFieldName); } } useMemory = true; } } } } getMonItem++; } }
void *findInt(struct StringTable *st, int key) { return findString(st, makeStringFromInt(key)); }
int main(int argc, const char * argv[]) { /* int var1 = 100; int var2 = 200; //swap1(var1, var2); swap2(&var1, &var2); printf("main 函数中两个值为 var1 = %d , var2 = %d \n",var1,var2); */ findString(); //想在内存中,放入 10 这个值, //由编译器决定 10 保存在哪块内存中 //我们如果想用这个值,起了一个名字 a //a 只是临时性的指向 10 所在内存 //&a 取出 10 所在的内存地址,内存地址是固定的 /* //买眼镜的淘宝店:宝龙眼镜 int taobao =22; int jd = 22; int paipai = 22; //三家网店,都在同一个厂里拿货,真实地址 int *p = &taobao; */ /* int a = 10; //&a 地址是很长的数字 0x7fff5fbff8ac //*pointer 使用带 * 的变量 pointer 专门保存上面的地址值 int *pointer; pointer = &a; printf("变量 a 所指向的内存地址为 %p \n",&a); printf("指针 pointer 的值为 %p \n",pointer); */ /* arr [0] 1 2 3 4 5 6 ----------------------------- | 1 | 2 | 3 | 4 | 5 | 6 | 7 | ----------------------------- 地址 arr arr+1 arr+2 ..... 取值 *arr *(arr+1) *(arr+2)..... */ /* //指针操作一维数组 int arr[] = {1,2,3,4,5,6,7}; //取整个数组的地址,实际就是得到数组第一个元素的地址 printf("arr 的地址为 %p \n",&arr); printf("arr 的起始地址为 %p \n",arr); printf("arr 第二个元素地址 %p \n",(arr+1)); printf("int 类型长度为 %ld \n",sizeof(int)); printf("%ld \n",sizeof(arr)); printf("%ld \n",sizeof(*arr)); */ /* 下标法 arr2[00] 01 02 03 ----------------- | 1 | 2 | 3 | 4 | ----------------- 指针 row1+0 +1 +2 +3 arr2[10] 11 12 13 ----------------- | 5 | 6 | 7 | 8 | ----------------- row2+0 +1 +2 +3 20 21 22 [2][3] -------------------- | 9 | 10 | 11 | 12 | -------------------- row3+0 +1 +2 +3 第二维 ------------------------ | row1 | row2 | row3 | ------------------------ arr2 arr2+4 arr2+8 */ /* //指针操作二维数组 int arr2[3][4]={ {1,2,3,4}, {5,6,7,8}, {9,10,11,12} }; printf("下标法,取出数组2 中第一个数据 %d \n",arr2[0][0]); //纵向,取出每行首地址 printf("指针法,取出数组2 中第一行第一列数据 %d \n",**arr2); printf("指针法,取出数组2 中第二行第一列数据 %d \n",**(arr2+1)); printf("指针法,取出数组2 中第三行第一列数据 %d \n",**(arr2+2)); //横向,取出每列的地址 printf("指针法,取出数组2 中第一行第二列数据 %d \n",*(*arr2+1)); printf("指针法,取出数组2 中第一行第二列地址 %p \n",*arr2+1); printf("下标法,取出数组2 中最后一个数据 %d \n",arr2[2][3]); // arr2 本身指向第一行、第一列的地址 // arr2+2 指向第三行、第一列的地址 // *(arr2+2) 是地址,横向移动 // *(arr2+2)+3 移动到第三行、第四列的地址 // *() 取出这个地址中的值 printf("指针法,取出数组2 中最后一个数据 %d \n",*(*(arr2+2)+3)); */ return 0; }
/* * Do the substitute command. * The current line is set to the last substitution done. */ static void subCommand(const char *cmd, int num1, int num2) { char *cp, *oldStr, *newStr, buf[USERSIZE]; int delim, oldLen, newLen, deltaLen, offset; LINE *lp, *nlp; int globalFlag, printFlag, didSub, needPrint; if (bad_nums(num1, num2, "substitute")) return; globalFlag = FALSE; printFlag = FALSE; didSub = FALSE; needPrint = FALSE; /* * Copy the command so we can modify it. */ strcpy(buf, cmd); cp = buf; if (isblank(*cp) || (*cp == '\0')) { bb_error_msg("bad delimiter for substitute"); return; } delim = *cp++; oldStr = cp; cp = strchr(cp, delim); if (cp == NULL) { bb_error_msg("missing 2nd delimiter for substitute"); return; } *cp++ = '\0'; newStr = cp; cp = strchr(cp, delim); if (cp) *cp++ = '\0'; else cp = (char*)""; while (*cp) switch (*cp++) { case 'g': globalFlag = TRUE; break; case 'p': printFlag = TRUE; break; default: bb_error_msg("unknown option for substitute"); return; } if (*oldStr == '\0') { if (searchString[0] == '\0') { bb_error_msg("no previous search string"); return; } oldStr = searchString; } if (oldStr != searchString) strcpy(searchString, oldStr); lp = findLine(num1); if (lp == NULL) return; oldLen = strlen(oldStr); newLen = strlen(newStr); deltaLen = newLen - oldLen; offset = 0; nlp = NULL; while (num1 <= num2) { offset = findString(lp, oldStr, oldLen, offset); if (offset < 0) { if (needPrint) { printLines(num1, num1, FALSE); needPrint = FALSE; } offset = 0; lp = lp->next; num1++; continue; } needPrint = printFlag; didSub = TRUE; dirty = TRUE; /* * If the replacement string is the same size or shorter * than the old string, then the substitution is easy. */ if (deltaLen <= 0) { memcpy(&lp->data[offset], newStr, newLen); if (deltaLen) { memcpy(&lp->data[offset + newLen], &lp->data[offset + oldLen], lp->len - offset - oldLen); lp->len += deltaLen; } offset += newLen; if (globalFlag) continue; if (needPrint) { printLines(num1, num1, FALSE); needPrint = FALSE; } lp = lp->next; num1++; continue; } /* * The new string is larger, so allocate a new line * structure and use that. Link it in place of * the old line structure. */ nlp = xmalloc(sizeof(LINE) + lp->len + deltaLen); nlp->len = lp->len + deltaLen; memcpy(nlp->data, lp->data, offset); memcpy(&nlp->data[offset], newStr, newLen); memcpy(&nlp->data[offset + newLen], &lp->data[offset + oldLen], lp->len - offset - oldLen); nlp->next = lp->next; nlp->prev = lp->prev; nlp->prev->next = nlp; nlp->next->prev = nlp; if (curLine == lp) curLine = nlp; free(lp); lp = nlp; offset += newLen; if (globalFlag) continue; if (needPrint) { printLines(num1, num1, FALSE); needPrint = FALSE; } lp = lp->next; num1++; } if (!didSub) bb_error_msg("no substitutions found for \"%s\"", oldStr); }
//--------------------------------------------------------------------------- // Func: bool CScene::convert(char *aseFilename) // // Desc: // The main conversion loop. // All the string comparisons are case insensitive // // Returns 1 if conversion successful // 0 if unsuccessful // // Note: Searches the file twice. The first is for "critical" init data, // such as the number of checkpoints or number of players, which in // turn is used to allocate an array big enough for all the potential // data. //--------------------------------------------------------------------------- // bool CScene::convert(char *aseFilename) { bool goodToGo = 0; goodToGo = openFile(aseFilename); if(goodToGo) { track.setFileStream (&aseStream); model.setTexPointer (&texture); track.model.setTexPointer(&texture); texture.setFileStream (&aseStream); light.setFileStream (&aseStream); track.spline.setFileStream(&aseStream); spline.setFileStream (&aseStream); track.setFileStream (&aseStream); track.model.setFileStream (&aseStream); model.setFileStream (&aseStream); //------------------------------- // # scan for init / critical values first # //------------------------------- //track.setFileStream(aseStream); track.initGates(); //track.setFileStream(aseStream); track.initStartPos(); //track.setFileStream(aseStream); track.initPowerups(); // Go back to the beginning of the file aseStream.clear(); aseStream.seekg(0, ios::beg); //------------------------------- // Now scan for everything //------------------------------- while(!aseStream.eof()) { aseStream >> buffer; // aseStream.getline(buffer, sizeof(buffer)); if( !_stricmp("*MATERIAL", buffer) ) // found a texture { // cout << "Found a texture" << endl; //texture.setFileStream(aseStream); texture.add(); } else if( !_stricmp("*LIGHTOBJECT", buffer) ) // we found a light { //light.setFileStream(aseStream); light.add(); } else if( !_stricmp("*SHAPEOBJECT", buffer) ) // we found a spline { findString("*NODE_NAME"); // get the name memset(buffer, '\0', sizeof(char) * CONV_BUFFER_LEN); aseStream.getline(buffer, sizeof(char) * CONV_BUFFER_LEN); char seps[] = " -_,\""; char *splineName; splineName = strtok( _strlwr(buffer), seps); // cout << "Found a spline with name: " << splineName << endl; if( !_stricmp(splineName, "hidden") ) { ; // do nothing; we don't want to draw (therefore, not load) this object } else if( !_stricmp(splineName, "trackspline") ) { // cout << "Adding track spline..." << endl; //track.spline.setFileStream(aseStream); track.spline.add(splineName); } else if( !_stricmp(splineName, "mapspline") ) { error.msg( "Found a map spline. Skipping. (Not implemented yet)." ); } else { // cout << "Adding spline..." << endl; //spline.setFileStream(aseStream); spline.add(splineName); } } else if( !strcmp("*GEOMOBJECT", buffer) ) // we found a model { findString("*NODE_NAME"); // get the name //------------------ // Parse model name //------------------ memset(buffer, '\0', sizeof(char) * CONV_BUFFER_LEN); aseStream.getline(buffer, sizeof(char) * CONV_BUFFER_LEN); char seps[] = " -_,\""; char *token; token = strtok( _strlwr(buffer), seps); //------------------------- // Get game and model data //------------------------- if( !_stricmp(token, "hidden") ) { ; // do nothing; we don't want to draw (therefore, not load) this object } else if( !_stricmp(token, "laps") ) { //track.setFileStream(aseStream); track.getLaps(); } else if( !_stricmp(token, "powerup") ) { //track.setFileStream(aseStream); track.getPowerup(); } else if( !_stricmp(token, "startpos") ) { //track.setFileStream(aseStream); track.getStartPos(); } else if( !_stricmp(token, "playerstartpos") ) { //track.setFileStream(aseStream); findString( "*TM_POS" ); if(!aseStream.eof()) { aseStream >> track.playerStartPos[0] // swap y & z >> track.playerStartPos[2] >> track.playerStartPos[1]; track.playerStartPos[2] *= -1; // flip for 3ds } } else if( !_stricmp(token, "checkpoint") )
const char * Auth::getUser() { return findString(AUTH_USER); }
bool Page::findString(const String& target, TextCaseSensitivity caseSensitivity, FindDirection direction, bool shouldWrap) { return findString(target, (caseSensitivity == TextCaseInsensitive ? CaseInsensitive : 0) | (direction == FindDirectionBackward ? Backwards : 0) | (shouldWrap ? WrapAround : 0)); }
const char * Auth::getUrl() { return findString(AUTH_URL); }
//---------------------------------------------------------------------------- CharString ProcessServer::searchLogFiles( CharString sFilemask, CharString sSearch, bool bRegExp, char nSearchLevel, bool bResolveClients ) { CharString sResult; RegExpM rxSearch; RegExpM rxClientId, rxLogin; Tree< unsigned int, String > trClientLookup; sSearch.lower(); // all search is performed case insensitive if( bRegExp ) rxSearch.regComp( sSearch ); if( bResolveClients ) rxClientId.regComp( STR("[Cc]lient ([0-9]+)[, ]") ); FindFile ff; CharString sMask = CharString().format("./Logs/%s.log",sFilemask.cstr()); ff.findFiles( sMask, false, false ); // sorted by date int nTotalFoundSize = 0; int nTotalSearchedSize = 0; int nTotalFilesSearched = 0; CharString sLine; dword tStart = Time::seconds(); bool bAbort = false; // search through all found files for( int i = 0 ; i < ff.fileCount() && !bAbort ; i++ ) { CharString sLocalFile( ff.file( i ) ); if( nSearchLevel == 2 ) // only list the files, not search them ? { CharString sFile = CharString().format("./Logs/%s", sLocalFile.cstr()) ; sResult += String().format("*** [%s] *** %s\r\n", Time::format( FileDisk::fileDate( sFile ),"%c").cstr(), sLocalFile.cstr() ); continue; } bool fileNamePrintedYet = false; CharString sText; CharString sTextOrig; int nCurPos = 0; try { CharString sFile = CharString().format("./Logs/%s",sLocalFile.cstr() ); char * pTemp = FileDisk::loadTextFile( sFile ); sText.copy( pTemp ).lower(); // pText is all lowercase, as it's used for case insensitive search sTextOrig = CharString().format("%s", pTemp ); // pTextOrig is orig-case, as it's used to build sResult delete pTemp; int nTextLen = sText.length(); nTotalSearchedSize += nTextLen; nTotalFilesSearched++; int pos = -1; // loop to find all occurences of the string while( nCurPos < nTextLen && ( pos = findString( sText, nCurPos, sSearch, &rxSearch, bRegExp ) ) >= 0 ) { if( !fileNamePrintedYet ) { if( nSearchLevel == 0 ) sResult += STR("\r\n\r\n"); CharString sFile = CharString().format("./Logs/%s", sLocalFile.cstr()) ; sResult += String().format("*** [%s] *** %s\r\n", Time::format( FileDisk::fileDate( sFile ),"%c").cstr(), sLocalFile.cstr() ); fileNamePrintedYet = true; } if( nSearchLevel == 1 ) // only check if there is a match in the file at all ? break; // find the matching line, this time in the original-case text nCurPos = findMatchingLine( sTextOrig, nCurPos + pos, sLine ); // need to resolve clientIds when found ? if( bResolveClients ) { int nClientIdPos = rxClientId.regFind( sLine ); if( nClientIdPos >= 0 ) // line holds a clientId ? { int nClientIdLen = rxClientId.getFindLen() - 8; // match length - static chars // extract the clientId CharString sClientId = sLine; sClientId.right( sClientId.length() - ( nClientIdPos + 7 ) ); sClientId.left( nClientIdLen ); int nClientId = CharString::strint(sClientId); CharString sResolvedClient(STR("")); if( trClientLookup.find( nClientId ).valid() ) // know this clientId already ? { sResolvedClient = trClientLookup[ nClientId ]; } else { // haven't seen it yet. Look it up. rxLogin.regComp( String().format( STR("\n../../.. ..:..:.. : Login client %d user ([^,\n]+), userId = ([0-9]+), "), nClientId ) ); if( rxLogin.regFind( sTextOrig ) >= 0 ) { sResolvedClient = rxLogin.getReplaceString( STR(" ( \\1 @\\2 )") ); } else { // not found yet ? Try alternate way to resolve it rxLogin.regComp( String().format( STR("\n../../.. ..:..:.. : Client %d login, id = ([^\r]+)"), nClientId ) ); if( rxLogin.regFind( sTextOrig ) >= 0 ) { sResolvedClient = rxLogin.getReplaceString( STR(" ( \\1 )") ); } // no further "else". If it's not found the result is left blank } trClientLookup[ nClientId ] = sResolvedClient; } if( sResolvedClient != "" ) // got something to insert ? sLine.insert( sResolvedClient, nClientIdPos + nClientIdLen + 7 ); } } // done resolving clientId // add the found line to the result nTotalFoundSize += sLine.length(); sResult += sLine; // abort conditions if( nTotalFoundSize > 300000 ) { sResult += STR("\r\n\r\n*** Result too large, search aborted"); bAbort = true; break; } } } catch( ... ) { return STR("Failed"); } } if( sResult.length() == 0 ) sResult = STR("No results"); else sResult += STR("\r\nDone..."); sResult += CharString().format( STR("\r\nSearched %d file(s) containing %d bytes within %d seconds. Result is %d bytes."), nTotalFilesSearched, nTotalSearchedSize, Time::seconds() - tStart, nTotalFoundSize ); return sResult; }
bool Editor::findString(const String& target, bool forward, bool caseFlag, bool wrapFlag, bool startInSelection) { FindOptions options = (forward ? 0 : Backwards) | (caseFlag ? 0 : CaseInsensitive) | (wrapFlag ? WrapAround : 0) | (startInSelection ? StartInSelection : 0); return findString(target, options); }
static void testFindString(void) { test(findString("cad", "abracadabra", 0), 4); test(findString("cad", "abracadabra", 6), -1); test(findString("abr", "abracadabra", 6), 7); }