main(){ char *s0 = "abcd", *s1 = "efg", *s2 = "def", st[MAXLEN]; strCat(st, s0); strCat(st, s1); printf("New st is %s.\n", st); strnCpy(s1, st, 2); printf("%s\n", st); return 0; }
void strCatQ(char **str,char *text,int len) { // cat quoted if (len<0) len = strlen(text); strCat(str,"\"",1); for(;len>0;len--,text++) { if (*text=='"') { strCat(str,"\\\"",2); } else strCat(str,text,1); } strCat(str,"\"",1); }
const char* FileMgr::name(const char* ipath) { String s(ipath); int slen = s.len(); int pos = s.find_last_of('/', slen - 2); if (s[slen-1] == '/') { return strCat(s.substr(pos + 1, slen - (pos + 2))); } else { return strCat(s.substr(pos + 1)); } }
const char* FileMgr::basepath(const char* ipath) { String s(ipath); int pos = s.find_last_of('/'); int pos2 = s.find_last_of('.'); if (pos2 == String::npos || pos2 < pos) { return strCat(ipath); } else { return strCat(s.substr(0, pos2)); } }
const char* FileMgr::workDir() { const int kBufLen = 1024; char buf[kBufLen]; _getcwd(buf, kBufLen); strReplace(buf, '\\', '/'); return strCat(buf, "/"); }
const char* FileMgr::path(const char* ipath) { String s(ipath); int pos = s.find_last_of('/', s.len() - 2); if (pos == String::npos) return ""; else return strCat(s.substr(0, pos+1).c_str()); }
void FileMgr::internalOperateCB(const char* file) { WTON_ASSERT(gSzs.len()); char* gSz = gSzs.back(); OperateCB gCB = gCBs.back(); InternalOperateCB gCB2 = gCB2s.back(); String subpat(strCat(file, gSz + 1)); operate(subpat.cStr(), false, gCB, gCB2); }
int gmodem_collect_out(gmodem *g, char *buf, int len) { int r = len; int pc = szCollect; if (r>szCollect) r = szCollect; // not more than if ( strLength(tmpFile)==0 && r>=2 ) { // skip first '\r\n' strCat(&tmpFile,buf+2,r-2); szCollect-=r-2; } else { strCat(&tmpFile,buf,r); szCollect-=r; } //printf("(%*.*s) rest %d",len,len,buf,szCollect); gmodem_logf(g,5,"collect_gmodem_out: got %d rest %d, expect_at_begin %d move:%d",len,szCollect,pc,r); if (g->logLevel>=5) if ( szCollect<200) hex_dump("buf",buf,len); memmove(g->in,g->in+r,g->in_len-r); g->in_len-=r; // clear gmodem buffer... if (szCollect<=0) { hex_dump("do_lines",g->in,g->in_len); g->mode = 0; // return back to read gmodem_do_lines(g); // proceed rest of lines } return 0; }
/*********************************************************************************************************************************** End the command ***********************************************************************************************************************************/ void cmdEnd(int code, const String *errorMessage) { FUNCTION_LOG_BEGIN(logLevelTrace); FUNCTION_LOG_PARAM(INT, code); FUNCTION_LOG_PARAM(STRING, errorMessage); FUNCTION_LOG_END(); ASSERT(cfgCommand() != cfgCmdNone); // Skip this log message if it won't be output. It's not too expensive but since we skipped cmdBegin(), may as well. if (logWill(cfgLogLevelDefault())) { MEM_CONTEXT_TEMP_BEGIN() { // Basic info on command end String *info = strNewFmt("%s command end: ", cfgCommandName(cfgCommand())); if (errorMessage == NULL) { strCat(info, "completed successfully"); if (cfgOptionValid(cfgOptLogTimestamp) && cfgOptionBool(cfgOptLogTimestamp)) strCatFmt(info, " (%" PRIu64 "ms)", timeMSec() - timeBegin); } else strCat(info, strPtr(errorMessage)); LOG(cfgLogLevelDefault(), 0, strPtr(info)); } MEM_CONTEXT_TEMP_END(); } // Reset timeBegin in case there is another command following this one timeBegin = timeMSec(); FUNCTION_LOG_RETURN_VOID(); }
/* 测试 strCat() 函数 */ int main(void) { /* 下面三条语句在编译时不会报任何错误,但在执行时,会抛出段错误异常. * 因为 p 指向的是字符常量区,如果改变这里面的内容,其后果没有定义. * char *p = "tian"; char *q = " xia"; strCat(p, q); */ char p[20] = "tian"; char *q = " xia"; strCat(p, q); printf("%s\n", p); return 0; }
void CCommandLineDisplay::InputDelete (void) // InputDelete // // Delete characters from input buffer { if (m_sInput.GetLength() > 0 && m_iCursorPos < m_sInput.GetLength()) { if (m_iCursorPos == 0) m_sInput = strSubString(m_sInput, 1, -1); else m_sInput = strCat(strSubString(m_sInput, 0, m_iCursorPos), strSubString(m_sInput, m_iCursorPos+1, -1)); m_bInvalid = true; } }
void CCommandLineDisplay::InputBackspace (void) // InputBackspace // // Delete characters from input buffer { if (m_iCursorPos > 0) { if (m_iCursorPos == m_sInput.GetLength()) m_sInput = strSubString(m_sInput, 0, m_sInput.GetLength() - 1); else m_sInput = strCat(strSubString(m_sInput, 0, m_iCursorPos - 1), strSubString(m_sInput, m_iCursorPos, -1)); m_iCursorPos--; m_bInvalid = true; } }
VOID FillComboWithOutputFormats(HWND hWnd, OUTPUTFORMAT *formats, int nFmtCount) { SendMessage(hWnd, CB_RESETCONTENT, 0, 0); LPTSTR str = NULL; for (int i=0; i < nFmtCount; i++) { str = strCat(formats[i].strName, TEXT(" ("), formats[i].strDescription, TEXT(")"), NULL); // the combo will make a copy of the passed string SendMessage(hWnd, CB_ADDSTRING, 0, (LPARAM) str); strFree(str); } // don't leave a null selection SendMessage(hWnd, CB_SETCURSEL, (WPARAM)0, 0); }
int main() { static char message[20] = "Salut"; static char ch2[] = "hello"; static char ch1[] = "hi"; printf("\nEntrez un message\n"); getS(message,25); printf("\nAffichage message : "); putS(message); strCpy(ch2,ch1); printf("\nAffichage message apres copy de hi dans hello: "); putS(ch2); printf("%d",strLen("Plop8")); printf("\nstrCmp1 : %d",strCmp("plop","plop")); printf("\nstrCmp2 : %d",strCmp("ABCD","ABEFG")); printf("\nstrCmp3 : %d",strCmp("plop","plo")); printf("\nstrCat : "); strCat(message," Denis"); putS(message); }
void dbStrFetch(database *db,char **str) { // есть два варианта - и еще тема - если пустой селект ! while( db_fetch(db) ) { db_col *c; int i; strCat(str,"[",-1); for(i=0,c=db->out.cols;i<db->out.count;i++,c++) { strCat(str,c->name,-1); strCat(str,":",-1); char *t = db_text(c); if ( (c->type == dbInt) || (c->type == dbNumber)) { if (*t==0) strCat(str,"0",-1); else strCat(str,t,-1); } else { strCatQ(str,db_text(c),-1); // do it for a string... } if (i+1<db->out.count) strCat(str,",",-1); } strCat(str,"]",-1); } }
int main() { char str[80]; char str1[80]; char *ptr; int len; printf("input string: "); gets(str); printf("原始字串: \"%s\"\n", str); len = strLen(str); printf("字串\"%s\"的長度為: %d\n", str, len); printf("複製字串: \"%s\"\n", strCpy(str1, str)); printf("請輸入欲連接的字串: "); gets(str1); printf("欲連接字串: \"%s\"\n", str1); ptr = strCat(str, str1); printf("連接結果的字串: \"%s\"\n", ptr); printf("請輸入欲比較的字串: "); gets(str1); printf("欲比較的字串: \"%s\"\n", str1); printf("字串比較結果: %d\n", strCmp(str, str1)); }
int main(){ str_t *s = strNew("Testing"); str_t *s2 = strNew(" this thing \n"); str_t *s3 = strNew(NULL); strCat(s, s2); strCpy(s3, s); strAppend(s3, "aaaaa"); printf("%lu, %lu, %lu %s\n", s->len, s->size, strlen(s->str), s->str); printf("%lu, %lu, %lu %s\n", s3->len, s3->size, strlen(s3->str), s3->str); str_t *c = strNew("testing"); strCpy(s, c); // strCpy(s2, c); printf("compare: %d\n", strCmp(s, s2)); strDel(s); strDel(s2); strDel(s3); return 0; }
int onDbRequest(Socket *sock, vssHttp *req, SocketMap *map) { // Генерация статистики по серверу char buf[1024]; httpSrv *srv = (void*)sock->pool; strSetLength(&srv->buf,0); // ClearResulted vss r=req->B; strCat(&srv->buf,r.data,r.len); char *sql = srv->buf; printf("DB->REQ:<%*.*s>\n",VSS(req->B)); if (strncmp(r.data,"select",6)==0) { // get a data if (db_select(db,sql)<=0) { // error here ... SocketPrintHttp(sock,req,"-%s",db->error); return 1; } strSetLength(&srv->buf,0); dbStrFetch(db,&srv->buf); SocketSendHttp(sock,req,srv->buf,-1); return 1; } else { //exec a result if (db_exec_once(db,sql)<=0) { // error here SocketPrintHttp(sock,req,"-%s",db->error); db_rollback(db); return 1; } db_commit(db); // anyqway SocketPrintHttp(sock,req,"+1 OK"); return 1; } /* sprintf(buf,"{clients:%d,connects:%d,requests:%d,mem:%d,serverTime:'%s',pps:%d}",arrLength(srv->srv.sock)-1, srv->srv.connects, srv->srv.requests, os_mem_used(), szTimeNow, (srv->readLimit.pValue+srv->readLimit.ppValue)/2); */ SocketPrintHttp(sock,req,"%s","-not implemented yet"); // Flash Results as httpreturn 1; // OK - generated return 1; }
/* Borrow part of code from libwww2 came with Mosaic distribution */ static void gopherToHTML(GopherStateData * gopherState, char *inbuf, int len) { char *pos = inbuf; char *lpos = NULL; char *tline = NULL; LOCAL_ARRAY(char, line, TEMP_BUF_SIZE); LOCAL_ARRAY(char, tmpbuf, TEMP_BUF_SIZE); String outbuf = StringNull; char *name = NULL; char *selector = NULL; char *host = NULL; char *port = NULL; char *escaped_selector = NULL; const char *icon_url = NULL; char gtype; StoreEntry *entry = NULL; memset(tmpbuf, '\0', TEMP_BUF_SIZE); memset(line, '\0', TEMP_BUF_SIZE); entry = gopherState->entry; if (gopherState->conversion == HTML_INDEX_PAGE) { char *html_url = html_quote(storeUrl(entry)); gopherHTMLHeader(entry, "Gopher Index %s", html_url); storeAppendPrintf(entry, "<p>This is a searchable Gopher index. Use the search\n" "function of your browser to enter search terms.\n" "<ISINDEX>\n"); gopherHTMLFooter(entry); /* now let start sending stuff to client */ storeBufferFlush(entry); gopherState->HTML_header_added = 1; return; } if (gopherState->conversion == HTML_CSO_PAGE) { char *html_url = html_quote(storeUrl(entry)); gopherHTMLHeader(entry, "CSO Search of %s", html_url); storeAppendPrintf(entry, "<P>A CSO database usually contains a phonebook or\n" "directory. Use the search function of your browser to enter\n" "search terms.</P><ISINDEX>\n"); gopherHTMLFooter(entry); /* now let start sending stuff to client */ storeBufferFlush(entry); gopherState->HTML_header_added = 1; return; } inbuf[len] = '\0'; if (!gopherState->HTML_header_added) { if (gopherState->conversion == HTML_CSO_RESULT) gopherHTMLHeader(entry, "CSO Search Result", NULL); else gopherHTMLHeader(entry, "Gopher Menu", NULL); strCat(outbuf, "<PRE>"); gopherState->HTML_header_added = 1; gopherState->HTML_pre = 1; } while ((pos != NULL) && (pos < inbuf + len)) { if (gopherState->len != 0) { /* there is something left from last tx. */ xstrncpy(line, gopherState->buf, gopherState->len + 1); if (gopherState->len + len > TEMP_BUF_SIZE) { debug(10, 1) ("GopherHTML: Buffer overflow. Lost some data on URL: %s\n", storeUrl(entry)); len = TEMP_BUF_SIZE - gopherState->len; } lpos = (char *) memccpy(line + gopherState->len, inbuf, '\n', len); if (lpos) *lpos = '\0'; else { /* there is no complete line in inbuf */ /* copy it to temp buffer */ if (gopherState->len + len > TEMP_BUF_SIZE) { debug(10, 1) ("GopherHTML: Buffer overflow. Lost some data on URL: %s\n", storeUrl(entry)); len = TEMP_BUF_SIZE - gopherState->len; } xmemcpy(gopherState->buf + gopherState->len, inbuf, len); gopherState->len += len; return; } /* skip one line */ pos = (char *) memchr(pos, '\n', len); if (pos) pos++; /* we're done with the remain from last tx. */ gopherState->len = 0; *(gopherState->buf) = '\0'; } else { lpos = (char *) memccpy(line, pos, '\n', len - (pos - inbuf)); if (lpos) *lpos = '\0'; else { /* there is no complete line in inbuf */ /* copy it to temp buffer */ if ((len - (pos - inbuf)) > TEMP_BUF_SIZE) { debug(10, 1) ("GopherHTML: Buffer overflow. Lost some data on URL: %s\n", storeUrl(entry)); len = TEMP_BUF_SIZE; } if (len > (pos - inbuf)) { xmemcpy(gopherState->buf, pos, len - (pos - inbuf)); gopherState->len = len - (pos - inbuf); } break; } /* skip one line */ pos = (char *) memchr(pos, '\n', len); if (pos) pos++; } /* at this point. We should have one line in buffer to process */ if (*line == '.') { /* skip it */ memset(line, '\0', TEMP_BUF_SIZE); continue; } switch (gopherState->conversion) { case HTML_INDEX_RESULT: case HTML_DIR:{ tline = line; gtype = *tline++; name = tline; selector = strchr(tline, TAB); if (selector) { *selector++ = '\0'; host = strchr(selector, TAB); if (host) { *host++ = '\0'; port = strchr(host, TAB); if (port) { char *junk; port[0] = ':'; junk = strchr(host, TAB); if (junk) *junk++ = 0; /* Chop port */ else { junk = strchr(host, '\r'); if (junk) *junk++ = 0; /* Chop port */ else { junk = strchr(host, '\n'); if (junk) *junk++ = 0; /* Chop port */ } } if ((port[1] == '0') && (!port[2])) port[0] = 0; /* 0 means none */ } /* escape a selector here */ escaped_selector = xstrdup(rfc1738_escape_part(selector)); switch (gtype) { case GOPHER_DIRECTORY: icon_url = mimeGetIconURL("internal-menu"); break; case GOPHER_HTML: case GOPHER_FILE: icon_url = mimeGetIconURL("internal-text"); break; case GOPHER_INDEX: case GOPHER_CSO: icon_url = mimeGetIconURL("internal-index"); break; case GOPHER_IMAGE: case GOPHER_GIF: case GOPHER_PLUS_IMAGE: icon_url = mimeGetIconURL("internal-image"); break; case GOPHER_SOUND: case GOPHER_PLUS_SOUND: icon_url = mimeGetIconURL("internal-sound"); break; case GOPHER_PLUS_MOVIE: icon_url = mimeGetIconURL("internal-movie"); break; case GOPHER_TELNET: case GOPHER_3270: icon_url = mimeGetIconURL("internal-telnet"); break; case GOPHER_BIN: case GOPHER_MACBINHEX: case GOPHER_DOSBIN: case GOPHER_UUENCODED: icon_url = mimeGetIconURL("internal-binary"); break; case GOPHER_INFO: icon_url = NULL; break; default: icon_url = mimeGetIconURL("internal-unknown"); break; } memset(tmpbuf, '\0', TEMP_BUF_SIZE); if ((gtype == GOPHER_TELNET) || (gtype == GOPHER_3270)) { if (strlen(escaped_selector) != 0) snprintf(tmpbuf, TEMP_BUF_SIZE, "<IMG border=\"0\" SRC=\"%s\"> <A HREF=\"telnet://%s@%s%s%s/\">%s</A>\n", icon_url, escaped_selector, rfc1738_escape_part(host), *port ? ":" : "", port, html_quote(name)); else snprintf(tmpbuf, TEMP_BUF_SIZE, "<IMG border=\"0\" SRC=\"%s\"> <A HREF=\"telnet://%s%s%s/\">%s</A>\n", icon_url, rfc1738_escape_part(host), *port ? ":" : "", port, html_quote(name)); } else if (gtype == GOPHER_INFO) { snprintf(tmpbuf, TEMP_BUF_SIZE, "\t%s\n", html_quote(name)); } else { if (strncmp(selector, "GET /", 5) == 0) { /* WWW link */ snprintf(tmpbuf, TEMP_BUF_SIZE, "<IMG border=\"0\" SRC=\"%s\"> <A HREF=\"http://%s/%s\">%s</A>\n", icon_url, host, rfc1738_escape_unescaped(selector + 5), html_quote(name)); } else { /* Standard link */ snprintf(tmpbuf, TEMP_BUF_SIZE, "<IMG border=\"0\" SRC=\"%s\"> <A HREF=\"gopher://%s/%c%s\">%s</A>\n", icon_url, host, gtype, escaped_selector, html_quote(name)); } } safe_free(escaped_selector); strCat(outbuf, tmpbuf); } else { memset(line, '\0', TEMP_BUF_SIZE); continue; } } else { memset(line, '\0', TEMP_BUF_SIZE); continue; } break; } /* HTML_DIR, HTML_INDEX_RESULT */ case HTML_CSO_RESULT:{ if (line[0] == '-') { int code, recno; char *s_code, *s_recno, *result; s_code = strtok(line + 1, ":\n"); s_recno = strtok(NULL, ":\n"); result = strtok(NULL, "\n"); if (!result) break; code = atoi(s_code); recno = atoi(s_recno); if (code != 200) break; if (gopherState->cso_recno != recno) { snprintf(tmpbuf, TEMP_BUF_SIZE, "</PRE><HR noshade size=\"1px\"><H2>Record# %d<br><i>%s</i></H2>\n<PRE>", recno, html_quote(result)); gopherState->cso_recno = recno; } else { snprintf(tmpbuf, TEMP_BUF_SIZE, "%s\n", html_quote(result)); } strCat(outbuf, tmpbuf); break; } else { int code; char *s_code, *result; s_code = strtok(line, ":"); result = strtok(NULL, "\n"); if (!result) break; code = atoi(s_code); switch (code) { case 200:{ /* OK */ /* Do nothing here */ break; } case 102: /* Number of matches */ case 501: /* No Match */ case 502: /* Too Many Matches */ { /* Print the message the server returns */ snprintf(tmpbuf, TEMP_BUF_SIZE, "</PRE><HR noshade size=\"1px\"><H2>%s</H2>\n<PRE>", html_quote(result)); strCat(outbuf, tmpbuf); break; } } } } /* HTML_CSO_RESULT */ default: break; /* do nothing */ } /* switch */ } /* while loop */ if (strLen(outbuf) > 0) { storeAppend(entry, strBuf(outbuf), strLen(outbuf)); /* now let start sending stuff to client */ storeBufferFlush(entry); } stringClean(&outbuf); return; }
void FileMgr::operate(const char* pattern, bool dirs, OperateCB cb, InternalOperateCB cb2) { // exactly one of these should be set WTON_ASSERT(cb == NULL || cb2 == NULL); WTON_ASSERT(cb || cb2); String pat(pattern); if (pat.endsWith("\\")) { pat = pat.substr(0, pat.len() - 1); } String ipath; // we'll be gentle, promise! char* sz = const_cast<char*>(pat.cStr()); bool wild = false; char* dir = NULL; while (*sz) { if (*sz == '/' || *sz == '\\') { if (wild) { *sz = 0; gSzs.push_back(sz); gCBs.push_back(cb); gCB2s.push_back(cb2); // recurse wildcard dirs to expand them operate(pat.cStr(), true, NULL, internalOperateCB); gSzs.pop_back(); gCBs.pop_back(); gCB2s.pop_back(); *sz = '\\'; return; } *sz = '\\'; dir = sz; } else if (*sz == '*') wild = true; ++sz; } #ifdef WTON_PC const char* qpat = pat.cStr(); WIN32_FIND_DATA data; // FindFirstFileEx ? HANDLE hResult = FindFirstFile(qpat, &data); if (hResult == INVALID_HANDLE_VALUE) return; if (dir) { *dir = 0; ipath = pat; *dir = '\\'; } do { // TODO: support .dotfiles if (startsWith(data.cFileName, ".")) continue; if (dirs == ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)) { String fullname(dir ? strCat(ipath, "\\", data.cFileName) : data.cFileName); if (dirs) { fullname += "\\"; } operateFile(fullname, cb, cb2); } } while (FindNextFile(hResult, &data)); FindClose(hResult); #else unused(dir); DIR* pdir; dirent* dent; pat.replace("\\", "/"); int pos = pat.find_last_of('/'); String patternn(pat.substr(pos + 1)); int pos2 = patternn.find('*'); String startPat, endPat; if (pos2 != String::npos) { startPat = patternn.substr(0, pos2); endPat = patternn.substr(pos2+1); } else { startPat = endPat = patternn; } pat = pat.substr(0, pos+1); WTON_ASSERT(pat[0] != '.' || pat[1] != '/', pat); pdir = opendir (strCat("./", pat.cStr())); if (pdir != NULL) { while ((dent = readdir (pdir))) { String name(dent->d_name); // TODO: support .dotfiles if (name.startsWith(".")) continue; String fullpath(strCat(pat, name)); bool entDir; { struct stat foo; int ret = stat(fullpath.cStr(), &foo); WTON_ASSERT(ret == 0); entDir = S_ISDIR(foo.st_mode); } if (dirs == entDir) { if (dirs) { fullpath += "/"; } if (name.startsWith(startPat.cStr()) && name.endsWith(endPat.cStr())) { operateFile(fullpath, cb, cb2); } } } (void) closedir (pdir); } else { // this just means the fixed path doesn't exist } #endif }
// this is probably going to take a few tries to get right, but bare with us! // note: ipath MUST be fully qualified for this to work under all circumstances const char* FileMgr::relativePath(const char* ipath, const char* newRoot) { // "." = "../src" = "../run" if (streq(ipath, "") || streq(ipath, ".")) { if (streq(newRoot, "../src/")) return "../run/"; WTON_ASSERT(0); } // "../src/_app/App.cpp" - "" = "../src/_app/App.cpp" if (streq(newRoot, "") || streq(newRoot, ".")) return strCat(ipath); // "../src/prims/prims.vcxproj" - "../src" = "prims/prims.vcxproj" // "../dev/dev.vcxproj" - "../src" = "../dev/dev.vcxproj" // "../src/rend_gl/" - "../src/rend" = "../rend_gl/" // find common root int i = 0; int slash = -1; while (true) { // TODO: WTON_ASSERT(ipath[i] != '\0'); if (newRoot[i] != '\0') { if (ipath[i] != newRoot[i]) break; else if (ipath[i] == '/') slash = i; } // we consumed the entire root else { if (ipath[i] == '/') return ipath + i + 1; else { WTON_ASSERT(slash != -1); break; } } ++i; } // for each path still in newRoot, we need a ../newPath int dirCount = 0; const char* s; for (s = newRoot + i; *s; ++s) { if (*s == '/') ++dirCount; } // if we don't end on a trailing slash we need to increment it one more if (s[-1] != '/') ++dirCount; return strCat(updirSpace(dirCount), ipath + slash + 1); }
/*********************************************************************************************************************************** Do cleanup and return result code ***********************************************************************************************************************************/ int exitSafe(int result, bool error, SignalType signalType) { FUNCTION_LOG_BEGIN(logLevelDebug); FUNCTION_LOG_PARAM(INT, result); FUNCTION_LOG_PARAM(BOOL, error); FUNCTION_LOG_PARAM(ENUM, signalType); FUNCTION_LOG_END(); // Report error if one was thrown if (error) { // Don't log the error if it has already been logged by Perl #ifdef HAVE_LIBPERL if (strcmp(errorMessage(), PERL_EMBED_ERROR) != 0) { #endif LogLevel logLevel = errorCode() == errorTypeCode(&AssertError) ? logLevelAssert : logLevelError; // Assert errors always output a stack trace if (logLevel == logLevelAssert) LOG(logLevel, errorCode(), "%s\nSTACK TRACE:\n%s", errorMessage(), errorStackTrace()); else { // Log just the error to non-debug levels LOG_INTERNAL(logLevel, LOG_LEVEL_MIN, logLevelDetail, 0, errorCode(), errorMessage()); // Log the stack trace debug levels if (logAny(logLevelDebug)) { LOG_INTERNAL( logLevel, logLevelDebug, LOG_LEVEL_MAX, 0, errorCode(), "%s\nSTACK TRACE:\n%s", errorMessage(), errorStackTrace()); } } #ifdef HAVE_LIBPERL } #endif result = errorCode(); } // Free protocol objects but ignore errors TRY_BEGIN() { protocolFree(); } TRY_END(); // Free Perl but ignore errors #ifdef HAVE_LIBPERL TRY_BEGIN() { perlFree(result); } TRY_END(); #endif // Log command end if a command is set if (cfgCommand() != cfgCmdNone) { String *errorMessage = NULL; // On error generate an error message if (result != 0) { // On process terminate if (result == errorTypeCode(&TermError)) { errorMessage = strNew("terminated on signal "); // Terminate from a child if (signalType == signalTypeNone) strCat(errorMessage, "from child process"); // Else terminated directly else strCatFmt(errorMessage, "[SIG%s]", exitSignalName(signalType)); } // Standard error exit message else if (error) errorMessage = strNewFmt("aborted with exception [%03d]", result); } cmdEnd(result, errorMessage); } // Release any locks but ignore errors TRY_BEGIN() { lockRelease(false); } TRY_END(); // Return result - caller should immediate pass this result to exit() FUNCTION_LOG_RETURN(INT, result); }
int _dump2str(char **s,char *data,int len) { strCat(s,data,len); return 1; }
/*********************************************************************************************************************************** Test Run ***********************************************************************************************************************************/ void testRun(void) { FUNCTION_HARNESS_VOID(); // ***************************************************************************************************************************** if (testBegin("strNew(), strNewBuf(), strNewN(), strEmpty(), strPtr(), strSize(), and strFree()")) { // We don't want this struct to grow since there are generally a lot of strings, so make sure it doesn't grow without us // knowing about it TEST_RESULT_UINT(sizeof(StringConst), TEST_64BIT() ? 16 : 12, "check StringConst struct size"); // Test the size macro TEST_RESULT_VOID(CHECK_SIZE(555), "valid size"); TEST_ERROR(CHECK_SIZE(STRING_SIZE_MAX + 1), AssertError, "string size must be <= 1073741824 bytes"); String *string = strNew("static string"); TEST_RESULT_STR(strPtr(string), "static string", "new with static string"); TEST_RESULT_INT(strSize(string), 13, "check size"); TEST_RESULT_BOOL(strEmpty(string), false, "is not empty"); TEST_RESULT_INT(strlen(strPtr(string)), 13, "check size with strlen()"); TEST_RESULT_CHAR(strPtr(string)[2], 'a', "check character"); TEST_RESULT_VOID(strFree(string), "free string"); // ------------------------------------------------------------------------------------------------------------------------- TEST_RESULT_STR(strPtr(strNewN("testmorestring", 4)), "test", "new string with size limit"); // ------------------------------------------------------------------------------------------------------------------------- Buffer *buffer = bufNew(8); memcpy(bufPtr(buffer), "12345678", 8); bufUsedSet(buffer, 8); TEST_RESULT_STR(strPtr(strNewBuf(buffer)), "12345678", "new string from buffer"); // ------------------------------------------------------------------------------------------------------------------------- string = strNewFmt("formatted %s %04d", "string", 1); TEST_RESULT_STR(strPtr(string), "formatted string 0001", "new with formatted string"); TEST_RESULT_PTR(strPtr(NULL), NULL, "null string pointer"); TEST_RESULT_VOID(strFree(string), "free string"); TEST_RESULT_VOID(strFree(NULL), "free null string"); } // ***************************************************************************************************************************** if (testBegin("STRING_STATIC()")) { TEST_RESULT_STR(strPtr(TEST_STRING), "a very interesting string!", "check static string"); TEST_RESULT_STR(strPtr(strSubN(TEST_STRING, 0, 6)), "a very", "read-only strSub() works"); } // ***************************************************************************************************************************** if (testBegin("strBase() and strPath()")) { TEST_RESULT_STR(strPtr(strBase(STRDEF(""))), "", "empty string"); TEST_RESULT_STR(strPtr(strBase(STRDEF("/"))), "", "/ only"); TEST_RESULT_STR(strPtr(strBase(STRDEF("/file"))), "file", "root file"); TEST_RESULT_STR(strPtr(strBase(STRDEF("/dir1/dir2/file"))), "file", "subdirectory file"); TEST_RESULT_STR(strPtr(strPath(STRDEF(""))), "", "empty string"); TEST_RESULT_STR(strPtr(strPath(STRDEF("/"))), "/", "/ only"); TEST_RESULT_STR(strPtr(strPath(STRDEF("/file"))), "/", "root path"); TEST_RESULT_STR(strPtr(strPath(STRDEF("/dir1/dir2/file"))), "/dir1/dir2", "subdirectory file"); } // ***************************************************************************************************************************** if (testBegin("strCat(), strCatChr(), and strCatFmt()")) { String *string = strNew("XXXX"); String *string2 = strNew("ZZZZ"); TEST_RESULT_STR(strPtr(strCat(string, "YYYY")), "XXXXYYYY", "cat string"); TEST_RESULT_SIZE(string->extra, 4, "check extra"); TEST_RESULT_STR(strPtr(strCatFmt(string, "%05d", 777)), "XXXXYYYY00777", "cat formatted string"); TEST_RESULT_SIZE(string->extra, 6, "check extra"); TEST_RESULT_STR(strPtr(strCatChr(string, '!')), "XXXXYYYY00777!", "cat chr"); TEST_RESULT_SIZE(string->extra, 5, "check extra"); TEST_RESULT_STR(strPtr(string2), "ZZZZ", "check unaltered string"); } // ***************************************************************************************************************************** if (testBegin("strDup()")) { const String *string = STRDEF("duplicated string"); String *stringDup = strDup(string); TEST_RESULT_STR(strPtr(stringDup), strPtr(string), "duplicated strings match"); TEST_RESULT_PTR(strDup(NULL), NULL, "duplicate null string"); } // ***************************************************************************************************************************** if (testBegin("strBeginsWith() and strBeginsWithZ()")) { TEST_RESULT_BOOL(strBeginsWith(STRDEF(""), STRDEF("aaa")), false, "empty string"); TEST_RESULT_BOOL(strBeginsWith(STRDEF("astring"), STRDEF("")), true, "empty begins with"); TEST_RESULT_BOOL(strBeginsWithZ(STRDEF("astring"), "astr"), true, "partial begins with"); TEST_RESULT_BOOL(strBeginsWithZ(STRDEF("astring"), "astring"), true, "equal strings"); } // ***************************************************************************************************************************** if (testBegin("strEndsWith() and strEndsWithZ()")) { TEST_RESULT_BOOL(strEndsWith(STRDEF(""), STRDEF(".doc")), false, "empty string"); TEST_RESULT_BOOL(strEndsWith(STRDEF("astring"), STRDEF("")), true, "empty ends with"); TEST_RESULT_BOOL(strEndsWithZ(STRDEF("astring"), "ing"), true, "partial ends with"); TEST_RESULT_BOOL(strEndsWithZ(STRDEF("astring"), "astring"), true, "equal strings"); } // ***************************************************************************************************************************** if (testBegin("strEq(), strEqZ(), strCmp(), strCmpZ()")) { TEST_RESULT_BOOL(strEq(STRDEF("equalstring"), STRDEF("equalstring")), true, "strings equal"); TEST_RESULT_BOOL(strEq(STRDEF("astring"), STRDEF("anotherstring")), false, "strings not equal"); TEST_RESULT_BOOL(strEq(STRDEF("astring"), STRDEF("bstring")), false, "equal length strings not equal"); TEST_RESULT_INT(strCmp(STRDEF("equalstring"), STRDEF("equalstring")), 0, "strings equal"); TEST_RESULT_INT(strCmp(STRDEF("a"), STRDEF("b")), -1, "a < b"); TEST_RESULT_INT(strCmp(STRDEF("b"), STRDEF("a")), 1, "b > a"); TEST_RESULT_BOOL(strEqZ(STRDEF("equalstring"), "equalstring"), true, "strings equal"); TEST_RESULT_BOOL(strEqZ(STRDEF("astring"), "anotherstring"), false, "strings not equal"); TEST_RESULT_BOOL(strEqZ(STRDEF("astring"), "bstring"), false, "equal length strings not equal"); TEST_RESULT_INT(strCmpZ(STRDEF("equalstring"), "equalstring"), 0, "strings equal"); TEST_RESULT_INT(strCmpZ(STRDEF("a"), "b"), -1, "a < b"); TEST_RESULT_INT(strCmpZ(STRDEF("b"), "a"), 1, "b > a"); } // ***************************************************************************************************************************** if (testBegin("strFirstUpper(), strFirstLower(), strUpper(), strLower()")) { TEST_RESULT_STR(strPtr(strFirstUpper(strNew(""))), "", "empty first upper"); TEST_RESULT_STR(strPtr(strFirstUpper(strNew("aaa"))), "Aaa", "first upper"); TEST_RESULT_STR(strPtr(strFirstUpper(strNew("Aaa"))), "Aaa", "first already upper"); TEST_RESULT_STR(strPtr(strFirstLower(strNew(""))), "", "empty first lower"); TEST_RESULT_STR(strPtr(strFirstLower(strNew("AAA"))), "aAA", "first lower"); TEST_RESULT_STR(strPtr(strFirstLower(strNew("aAA"))), "aAA", "first already lower"); TEST_RESULT_STR(strPtr(strLower(strNew("K123aBc"))), "k123abc", "all lower"); TEST_RESULT_STR(strPtr(strLower(strNew("k123abc"))), "k123abc", "already lower"); TEST_RESULT_STR(strPtr(strLower(strNew("C"))), "c", "char lower"); TEST_RESULT_STR(strPtr(strLower(strNew(""))), "", "empty lower"); TEST_RESULT_STR(strPtr(strUpper(strNew("K123aBc"))), "K123ABC", "all upper"); TEST_RESULT_STR(strPtr(strUpper(strNew("K123ABC"))), "K123ABC", "already upper"); TEST_RESULT_STR(strPtr(strUpper(strNew("c"))), "C", "char upper"); TEST_RESULT_STR(strPtr(strUpper(strNew(""))), "", "empty upper"); } // ***************************************************************************************************************************** if (testBegin("strQuote()")) { TEST_RESULT_STR(strPtr(strQuote(STRDEF("abcd"), STRDEF("'"))), "'abcd'", "quote string"); } // ***************************************************************************************************************************** if (testBegin("strReplaceChr()")) { TEST_RESULT_STR(strPtr(strReplaceChr(strNew("ABCD"), 'B', 'R')), "ARCD", "replace chr"); } // ***************************************************************************************************************************** if (testBegin("strSub() and strSubN()")) { TEST_RESULT_STR(strPtr(strSub(STRDEF("ABCD"), 2)), "CD", "sub string"); TEST_RESULT_STR(strPtr(strSubN(STRDEF("ABCD"), 1, 2)), "BC", "sub string with length"); } // ***************************************************************************************************************************** if (testBegin("strTrim()")) { TEST_RESULT_STR(strPtr(strTrim(strNew(""))), "", "trim empty"); TEST_RESULT_STR(strPtr(strTrim(strNew("X"))), "X", "no trim (one char)"); TEST_RESULT_STR(strPtr(strTrim(strNew("no-trim"))), "no-trim", "no trim (string)"); TEST_RESULT_STR(strPtr(strTrim(strNew(" \t\r\n"))), "", "all whitespace"); TEST_RESULT_STR(strPtr(strTrim(strNew(" \tbegin-only"))), "begin-only", "trim begin"); TEST_RESULT_STR(strPtr(strTrim(strNew("end-only\t "))), "end-only", "trim end"); TEST_RESULT_STR(strPtr(strTrim(strNew("\n\rboth\r\n"))), "both", "trim both"); TEST_RESULT_STR(strPtr(strTrim(strNew("begin \r\n\tend"))), "begin \r\n\tend", "ignore whitespace in middle"); } // ***************************************************************************************************************************** if (testBegin("strChr() and strTrunc()")) { TEST_RESULT_INT(strChr(STRDEF("abcd"), 'c'), 2, "c found"); TEST_RESULT_INT(strChr(STRDEF("abcd"), 'C'), -1, "capital C not found"); TEST_RESULT_INT(strChr(STRDEF("abcd"), 'i'), -1, "i not found"); TEST_RESULT_INT(strChr(STRDEF(""), 'x'), -1, "empty string - x not found"); String *val = strNew("abcdef"); TEST_ERROR( strTrunc(val, (int)(strSize(val) + 1)), AssertError, "assertion 'idx >= 0 && (size_t)idx <= this->size' failed"); TEST_ERROR(strTrunc(val, -1), AssertError, "assertion 'idx >= 0 && (size_t)idx <= this->size' failed"); TEST_RESULT_STR(strPtr(strTrunc(val, strChr(val, 'd'))), "abc", "simple string truncated"); strCat(val, "\r\n to end"); TEST_RESULT_STR(strPtr(strTrunc(val, strChr(val, 'n'))), "abc\r\n to e", "complex string truncated"); TEST_RESULT_STR(strPtr(strTrunc(val, strChr(val, 'a'))), "", "complete string truncated - empty string"); TEST_RESULT_INT(strSize(val), 0, "0 size"); TEST_RESULT_STR(strPtr(strTrunc(val, 0)), "", "test coverage of empty string - no error thrown for index 0"); } // ***************************************************************************************************************************** if (testBegin("strToLog() and strObjToLog()")) { TEST_RESULT_STR(strPtr(strToLog(STRDEF("test"))), "{\"test\"}", "format string"); TEST_RESULT_STR(strPtr(strToLog(NULL)), "null", "format null string"); char buffer[256]; TEST_RESULT_UINT(strObjToLog(NULL, (StrObjToLogFormat)strToLog, buffer, sizeof(buffer)), 4, "format null string"); TEST_RESULT_STR(buffer, "null", "check null string"); TEST_RESULT_UINT(strObjToLog(STRDEF("teststr"), (StrObjToLogFormat)strToLog, buffer, sizeof(buffer)), 11, "format string"); TEST_RESULT_STR(buffer, "{\"teststr\"}", "check string"); } // ***************************************************************************************************************************** if (testBegin("strSizeFormat()")) { TEST_RESULT_STR(strPtr(strSizeFormat(0)), "0B", "zero bytes"); TEST_RESULT_STR(strPtr(strSizeFormat(1023)), "1023B", "1023 bytes"); TEST_RESULT_STR(strPtr(strSizeFormat(1024)), "1KB", "1 KB"); TEST_RESULT_STR(strPtr(strSizeFormat(2200)), "2.1KB", "2.1 KB"); TEST_RESULT_STR(strPtr(strSizeFormat(1048576)), "1MB", "1 MB"); TEST_RESULT_STR(strPtr(strSizeFormat(20162900)), "19.2MB", "19.2 MB"); TEST_RESULT_STR(strPtr(strSizeFormat(1073741824)), "1GB", "1 GB"); TEST_RESULT_STR(strPtr(strSizeFormat(1073741824 + 107374183)), "1.1GB", "1.1 GB"); TEST_RESULT_STR(strPtr(strSizeFormat(UINT64_MAX)), "17179869183GB", "uint64 max"); } // ***************************************************************************************************************************** if (testBegin("strLstNew(), strLstAdd*(), strLstGet(), strLstMove(), strLstSize(), and strLstFree()")) { // Add strings to the list // ------------------------------------------------------------------------------------------------------------------------- StringList *list = NULL; MEM_CONTEXT_TEMP_BEGIN() { list = strLstNew(); for (int listIdx = 0; listIdx <= LIST_INITIAL_SIZE; listIdx++) { if (listIdx == 0) { TEST_RESULT_PTR(strLstAdd(list, NULL), list, "add null item"); } else TEST_RESULT_PTR(strLstAdd(list, strNewFmt("STR%02d", listIdx)), list, "add item %d", listIdx); } strLstMove(list, MEM_CONTEXT_OLD()); } MEM_CONTEXT_TEMP_END(); TEST_RESULT_INT(strLstSize(list), 9, "list size"); // Read them back and check values // ------------------------------------------------------------------------------------------------------------------------- for (unsigned int listIdx = 0; listIdx < strLstSize(list); listIdx++) { if (listIdx == 0) { TEST_RESULT_PTR(strLstGet(list, listIdx), NULL, "check null item"); } else TEST_RESULT_STR(strPtr(strLstGet(list, listIdx)), strPtr(strNewFmt("STR%02u", listIdx)), "check item %u", listIdx); } TEST_RESULT_VOID(strLstFree(list), "free string list"); TEST_RESULT_VOID(strLstFree(NULL), "free null string list"); }
/*********************************************************************************************************************************** Begin the command ***********************************************************************************************************************************/ void cmdBegin(bool logOption) { FUNCTION_LOG_BEGIN(logLevelTrace); FUNCTION_LOG_PARAM(BOOL, logOption); FUNCTION_LOG_END(); ASSERT(cfgCommand() != cfgCmdNone); // This is fairly expensive log message to generate so skip it if it won't be output if (logWill(cfgLogLevelDefault())) { MEM_CONTEXT_TEMP_BEGIN() { // Basic info on command start String *info = strNewFmt("%s command begin", cfgCommandName(cfgCommand())); if (logOption) { strCatFmt(info, " %s:", PROJECT_VERSION); // Add command parameters if they exist const StringList *commandParamList = cfgCommandParam(); if (strLstSize(commandParamList) != 0) { strCatFmt(info, " ["); for (unsigned int commandParamIdx = 0; commandParamIdx < strLstSize(commandParamList); commandParamIdx++) { const String *commandParam = strLstGet(commandParamList, commandParamIdx); if (commandParamIdx != 0) strCatFmt(info, ", "); if (strchr(strPtr(commandParam), ' ') != NULL) commandParam = strNewFmt("\"%s\"", strPtr(commandParam)); strCat(info, strPtr(commandParam)); } strCatFmt(info, "]"); } // Loop though options and add the ones that are interesting for (ConfigOption optionId = 0; optionId < CFG_OPTION_TOTAL; optionId++) { // Skip the option if it is not valid if (!cfgOptionValid(optionId)) continue; // If option was negated if (cfgOptionNegate(optionId)) strCatFmt(info, " --no-%s", cfgOptionName(optionId)); // If option was reset else if (cfgOptionReset(optionId)) strCatFmt(info, " --reset-%s", cfgOptionName(optionId)); // Else set and not default else if (cfgOptionSource(optionId) != cfgSourceDefault && cfgOptionTest(optionId)) { ConfigDefineOption optionDefId = cfgOptionDefIdFromId(optionId); // Don't show redacted options if (cfgDefOptionSecure(optionDefId)) strCatFmt(info, " --%s=<redacted>", cfgOptionName(optionId)); // Output boolean option else if (cfgDefOptionType(optionDefId) == cfgDefOptTypeBoolean) strCatFmt(info, " --%s", cfgOptionName(optionId)); // Output other options else { StringList *valueList = NULL; // Generate the values of hash options if (cfgDefOptionType(optionDefId) == cfgDefOptTypeHash) { valueList = strLstNew(); const KeyValue *optionKv = cfgOptionKv(optionId); const VariantList *keyList = kvKeyList(optionKv); for (unsigned int keyIdx = 0; keyIdx < varLstSize(keyList); keyIdx++) { strLstAdd( valueList, strNewFmt( "%s=%s", strPtr(varStr(varLstGet(keyList, keyIdx))), strPtr(varStrForce(kvGet(optionKv, varLstGet(keyList, keyIdx)))))); } } // Generate values for list options else if (cfgDefOptionType(optionDefId) == cfgDefOptTypeList) { valueList = strLstNewVarLst(cfgOptionLst(optionId)); } // Else only one value else { valueList = strLstNew(); strLstAdd(valueList, varStrForce(cfgOption(optionId))); } // Output options and values for (unsigned int valueListIdx = 0; valueListIdx < strLstSize(valueList); valueListIdx++) { const String *value = strLstGet(valueList, valueListIdx); strCatFmt(info, " --%s", cfgOptionName(optionId)); if (strchr(strPtr(value), ' ') != NULL) value = strNewFmt("\"%s\"", strPtr(value)); strCatFmt(info, "=%s", strPtr(value)); } } } } } LOG(cfgLogLevelDefault(), 0, strPtr(info)); } MEM_CONTEXT_TEMP_END(); } FUNCTION_LOG_RETURN_VOID(); }
BOOL OnNotify(HWND hDlg, LPNMHDR lpNMHdr) { //DEBUGMESSAGE(("OnNotify")); UINT uiCode = lpNMHdr->code; switch (uiCode) { case PSN_APPLY: { DEBUGMESSAGE(("OnNotify - PSN_APPLY")); DocumentPropDialogData *data = (DocumentPropDialogData *) GetWindowLongPtr(hDlg, DWL_USER); if (data == NULL) { DEBUGMESSAGE(("DocPropDlgProc - invalid internal data pointer")); return FALSE; } // which format combo should we use? LPTSTR format = NULL; if (IsDlgButtonChecked(hDlg, IDC_VECTOR_FORMAT_RADIOBOX) == BST_CHECKED) { INT sel = GetComboCurSel(GetDlgItem(hDlg, IDC_COMBO_VECTOR_FORMAT)); format = strDuplicate(g_vectorFormats[sel].strName); } else if (IsDlgButtonChecked(hDlg, IDC_RASTER_FORMAT_RADIOBOX) == BST_CHECKED) { INT sel = GetComboCurSel(GetDlgItem(hDlg, IDC_COMBO_RASTER_FORMAT)); format = strDuplicate(g_rasterFormats[sel].strName); } else { DEBUGMESSAGE(("DocPropDlgProc - unexpected condition")); return FALSE; } // get the output folder & validate it LPTSTR folder = NULL; if (!GetEditControlText(&folder, GetDlgItem(hDlg, IDC_OUTPUT_FOLDER))) { DEBUGMESSAGE(("DocPropDlgProc - could not get output folder text")); return FALSE; } if (!FolderExists(folder)) { ErrorMessage(hDlg, TEXT("Warning"), TEXT("The given output directory does not exist!")); return FALSE; } // get the output filename & validate it LPTSTR filename = NULL; if (!GetEditControlText(&filename, GetDlgItem(hDlg, IDC_OUTPUT_FILENAME))) { DEBUGMESSAGE(("DocPropDlgProc - could not get output filename text")); return FALSE; } if (!IsValidFilename(filename)) { LPTSTR temp = strCat(TEXT("The given output filename is not valid!\n"), TEXT("It should not contain any of the '"), g_strFileNameForbiddenChars, TEXT("' characters."), NULL); ErrorMessage(hDlg, TEXT("Warning"), temp); strFree(temp); return FALSE; } // get the raster conv options LPTSTR rasteropt = NULL; if (!GetEditControlText(&rasteropt, GetDlgItem(hDlg, IDC_IMAGEMAGICK_OPTIONS))) { DEBUGMESSAGE(("DocPropDlgProc - could not get raster conv opt text")); return FALSE; } // get the postgen cmd LPTSTR postgen = NULL; if (!GetEditControlText(&postgen, GetDlgItem(hDlg, IDC_POSTGEN_CMD))) { DEBUGMESSAGE(("DocPropDlgProc - could not get postgen cmd text")); return FALSE; } // get override checkbox status BOOL override = IsDlgButtonChecked(hDlg, IDC_OVERRIDE_CHECKBOX) == BST_CHECKED; // get crop checkbox BOOL crop = IsDlgButtonChecked(hDlg, IDC_CROP_CHECKBOX) == BST_CHECKED; // get open-output checkbox BOOL openout = IsDlgButtonChecked(hDlg, IDC_OPEN_VIEWER_CHECKBOX) == BST_CHECKED; // save all data in the EXTDEVMODE extdmSetPrivateData(data->m_pExtdmCurrent, format, filename, folder, rasteropt, postgen, override, openout, crop); // cleanup strFree(format); strFree(filename); strFree(folder); strFree(postgen); strFree(rasteropt); // call the _SET_RESULT callback PFNCOMPROPSHEET pfnComPropSheet = data->m_pfnComPropSheet; LONG lTemp = pfnComPropSheet( data->m_hComPropSheet, CPSFUNC_SET_RESULT, (LPARAM) data->m_hPropSheetAdded, CPSUI_OK ); return TRUE; } break; case PSN_RESET: break; case PSN_SETACTIVE: break; default: break; } return FALSE; }