END_TEST START_TEST(test_str_rtrim) { str_t *str = str_from_cstr("123\r\n "); str_rtrim(str); CHECK_STR(str, >= 3, == 3, "123"); str_free(str); str = str_new(0); str_rtrim(str); CHECK_STR(str, == STR_DEFAULT_CAPACITY, == 0, ""); str_free(str); }
int main(int argc, char **argv) { struct stem_cache *stem = stem_cache_new(stem_porters, NULL, 200); char buf[BUFSIZ + 1]; unsigned int i; buf[BUFSIZ] = '\0'; if (!stem) { return EXIT_FAILURE; } if (argc == 1) { while (fgets(buf, BUFSIZ, stdin)) { char *start; str_rtrim(buf); start = (char *) str_ltrim(buf); stem_cache_stem(stem, start); printf("%s\n", start); } } else { for (i = 1; i < argc; i++) { FILE *input = fopen(argv[i], "rb+"); if (!input) { fprintf(stderr, "failed to open file %s: %s\n", argv[i], strerror(errno)); stem_cache_delete(stem); return EXIT_FAILURE; } while (fgets(buf, BUFSIZ, input)) { char *start; str_rtrim(buf); start = (char *) str_ltrim(buf); stem_cache_stem(stem, start); printf("%s\n", start); } fclose(input); } } stem_cache_delete(stem); return EXIT_SUCCESS; }
static int server_try_setclientname(int client_id, const char *name) { int i; char trimmed_name[64]; /* trim the name */ str_copy(trimmed_name, str_ltrim(name), sizeof(trimmed_name)); str_rtrim(trimmed_name); dbg_msg("", "'%s' -> '%s'", name, trimmed_name); name = trimmed_name; /* check for empty names */ if(!name[0]) return -1; /* make sure that two clients doesn't have the same name */ for(i = 0; i < MAX_CLIENTS; i++) if(i != client_id && clients[i].state >= SRVCLIENT_STATE_READY) { if(strcmp(name, clients[i].name) == 0) return -1; } /* set the client name */ str_copy(clients[client_id].name, name, MAX_NAME_LENGTH); return 0; }
/* * 现在squid.conf中可以配置的debug_level等级只有连个 * 0:显示关键的信息 * 1:显示所有信息 * */ int addInfoLog(int type, const char* str) { time_t t; t = time(NULL); char timeStr[128]; snprintf(timeStr, sizeof(timeStr), "%s", logTime(t)); str_rtrim(timeStr, "\n"); log_open(); if(0 == type ) { file_size += fprintf(fp, "[%s]:%s\n", timeStr, str); } else if(1 == type && 1 == conf.debug_level) { file_size += fprintf(fp, "[%s]:%s\n", timeStr, str); } else if (2 == type) { file_size += fprintf(fp, "Error[%s]:%s\n", timeStr, str); } fflush(fp); if(file_size > LOG_ROTATE_SIZE) log_rotate(); // fclose(fp); return 1; }
/* returns < 0 on errors, 0 on timeout and > 0 on success. */ static int upscrecv(char *buf) { int res; /* NOTE: the serial port is set to use Canonical Mode Input Processing, which means ser_get_buf() either returns one line terminated with ENDCHAR, an error or times out. */ while (1) { res = ser_get_buf(upsfd, buf, UPSC_BUFLEN, input_timeout_sec, 0); if (res != 1) { break; } /* Only one character, must be ENDCHAR */ upsdebugx(3, "upscrecv: Empty line"); } if (res < 0) { upsdebug_with_errno(3, "upscrecv"); } else if (res == 0) { upsdebugx(3, "upscrecv: Timeout"); } else { upsdebugx(3, "upscrecv: %u bytes:\t'%s'", res-1, str_rtrim(buf, ENDCHAR)); } return res; }
/** Send formatted message to the logger service. * * @param session Initialized IPC session with the logger. * @param log Log to use. * @param level Verbosity level of the message. * @param message The actual message. * @return Error code of the conversion or EOK on success. */ static int logger_message(async_sess_t *session, log_t log, log_level_t level, char *message) { async_exch_t *exchange = async_exchange_begin(session); if (exchange == NULL) { return ENOMEM; } if (log == LOG_DEFAULT) log = default_log_id; // FIXME: remove when all USB drivers use libc logging explicitly str_rtrim(message, '\n'); aid_t reg_msg = async_send_2(exchange, LOGGER_WRITER_MESSAGE, log, level, NULL); int rc = async_data_write_start(exchange, message, str_size(message)); sysarg_t reg_msg_rc; async_wait_for(reg_msg, ®_msg_rc); async_exchange_end(exchange); /* * Getting ENAK means no-one wants our message. That is not an * error at all. */ if (rc == ENAK) rc = EOK; if (rc != EOK) { return rc; } return reg_msg_rc; }
void getSquidConf() { FILE* confFile; FILE* squidFile; char line[BUFSIZ]; if ((confFile = fopen("../etc/monitor.conf", "r")) == NULL) { perror("monitor.conf"); exit(1); } while (fgets(line, BUFSIZ, confFile) != NULL) { str_ltrim(line, "\t "); str_rtrim(line, "\t\r\n "); if (!strncmp(conf_deviceName, line, strlen(conf_deviceName))) { int i = 0; while (conf_device[i] = line[i + 1 + strlen(conf_deviceName)]) { i++; } //printf("%s\n", conf_device); } } }
/** Merge two paths together. * * e.g. (path1 = /data/dir, path2 = a/b) --> /data/dir/a/b * * @param path1 Path to which path2 will be appended. * @param path1_size Size of the path1 buffer. * @param path2 Path that will be appended to path1. */ static void merge_paths(char *path1, size_t path1_size, char *path2) { const char *delim = "/"; str_rtrim(path1, '/'); str_append(path1, path1_size, delim); str_append(path1, path1_size, path2); }
void macro_rtrim(macro **mp) { macro *m = *mp; if (!m) return; macro_rtrim(&m->next); if (m->next) return; if (m->type != MACRO_STR) return; str_rtrim(&m->str); if (m->str) return; macro_free(m); *mp = 0; }
static int blazer_vendor(const char *cmd) { const struct { const char *var; const int len; } information[] = { { "ups.mfr", 15 }, { "ups.model", 10 }, { "ups.firmware", 10 }, { NULL } }; char buf[SMALLBUF]; int i, index; /* * > [I\r] * < [#------------- ------ VT12046Q \r] * 012345678901234567890123456789012345678 * 0 1 2 3 */ if (blazer_command(cmd, buf, sizeof(buf)) < 39) { upsdebugx(2, "%s: short reply", __func__); return -1; } if (buf[0] != '#') { upsdebugx(2, "%s: invalid start character [%02x]", __func__, buf[0]); return -1; } for (i = 0, index = 1; information[i].var; index += information[i++].len+1) { char val[SMALLBUF]; snprintf(val, sizeof(val), "%.*s", information[i].len, &buf[index]); dstate_setinfo(information[i].var, "%s", str_rtrim(val, ' ')); } return 0; }
/** * Authenticate and set client info. * @param[in] session Client session. * @return Zero on success. */ zrad_status_t zradius_session_auth(zscope_t *scope, zsession_t *session) { zrad_status_t ret; VALUE_PAIR *reply_attrs = NULL; char reply_msg[PW_MAX_MSG_SIZE] = {0}; zclient_rules_t rules; zclient_rules_init(&rules); zrad_auth_req_t req; zrad_auth_prepare(scope, session, &req); ret = zrad_auth_request(scope->radh, &req, &reply_attrs, reply_msg); if (unlikely(ZRAD_OK != ret)) { str_rtrim(reply_msg); ZLOG(LOG_ERR, "%s: Session authentication failed for %s (code: %s, msg: %s)", scope->cfg->name, session->ip_str, zrad_decode_state(ret), reply_msg); goto end; } zrad_auth_parse(session, reply_attrs, &rules); if (unlikely(!rules.have.user_id || !rules.have.login)) { ZLOG(LOG_ERR, "%s: Session authentication failed for %s (login or user_id not found)", scope->cfg->name, session->ip_str); ret = ZRAD_OTHER; goto end; } zscope_session_rules_apply(scope, session, &rules); zrad_auth_log(scope, session, reply_attrs); end: zclient_rules_destroy(&rules); if (likely(reply_attrs)) rc_avpair_free(reply_attrs); return ret; }
int main(int argc, char *argv[]) { char ord[128]; char buf[128]; FILE *fp; int len, i; if (argc < 2) { fprintf(stderr, "Missing argument\n"); return EXIT_FAILURE; } strcpy(ord, argv[1]); len = strlen(ord); bubblesort_word(ord); printf("Input word: %s, sorted: %s\n", argv[1], ord); fp = fopen("ordalisti.txt", "r"); if (fp == NULL) { fprintf(stderr, "Unable to open ordalisti.txt\n"); return EXIT_FAILURE; } i = 0; while (fgets(buf, sizeof(buf), fp) > 0) { printf("\rWords checked: %d", i++); str_rtrim(buf); bubblesort_word(buf); if (!strcmp(ord, buf)) { printf("\r \rFound match: %s\n", buf); return EXIT_SUCCESS; } } printf("\nNo match found\n"); return EXIT_FAILURE; }
void ConfigFile::_open(void) { std::ifstream ifs(_filename); _sections.clear(); if (not ifs.is_open()) return ; std::string section; std::string line; std::size_t idx; while (std::getline(ifs, line)) { str_trim(line); if (line.empty()) continue ; if(line.front() == '[' and line.back() == ']') { section = line.substr(1, line.size() - 2); str_trim(section); } else if ((idx = line.find("=")) != std::string::npos) { std::string key(line.substr(0, idx - 1)); std::string value(line.substr(idx + 1)); _sections[section][str_rtrim(key)] = str_ltrim(value); } else { warn(std::string("In `") + _filename + "`: badly formated: `" + line + "`"); } } ifs.close(); }
main(int argc, char** argv) { int filedes1[2], filedes2[2]; int pid; FILE* ifTestFile; char line[BUFSIZ]; int ethNum = 0; int RxNum = 0; time_t updateTime; FILE* poolFile; FILE* RxTxFile; char strLine[BUFSIZ]; unsigned long dataCount = 0; float timeCount = 0.0; float inBandSpeed = 0.0; float outBandSpeed = 0.0; const char* ethName = "eth"; const char* RxBytesName = "RX bytes:"; char RxBytes[BUFSIZ]; char TxBytes[BUFSIZ]; char newUpdateTime[BUFSIZ]; char oldRxBytes[BUFSIZ]; char oldTxBytes[BUFSIZ]; char oldUpdateTime[BUFSIZ]; getSquidConf(); if (pipe(filedes1) == -1) { perror ("pipe"); exit(1); } if (pipe(filedes2) == -1) { perror ("pipe"); exit(1); } if ((pid = fork()) == 0) { dup2(filedes1[0], fileno(stdin)); /* Copy the reading end of the pipe. */ dup2(filedes2[1], fileno(stdout)); /* Copy the writing end of the pipe */ /* Uncomment this if you want stderr sent too. dup2(filedes2[1], fileno(stderr)); */ /* If execl() returns at all, there was an error. */ if (execl("/sbin/ifconfig", "ifconfig","-a", (char*)0)) { perror("execl"); exit(128); } } else if (pid == -1) { perror("fork"); exit(128); } else { FILE *program_input, *program_output, *output_file; int c; if ((program_input = fdopen(filedes1[1], "w")) == NULL) { perror("fdopen"); exit(1); } if ((program_output = fdopen(filedes2[0], "r")) == NULL) { perror("fdopen"); exit(1); } if ((output_file = fopen("/tmp/ifconfig.test", "w+")) == NULL) { perror ("ifconfig.test"); exit(1); } //fputs(argv[2], program_input); /* Write the string */ while ( (c = getc(program_output)) != EOF) { fputc(c, output_file); //printf("%c",c); close(filedes2[0]); } fclose(output_file); //Process ifconfig.test file if ((ifTestFile = fopen("/tmp/ifconfig.test", "r")) == NULL) { perror("ifTestFile"); exit(1); } while (fgets(line, BUFSIZ, ifTestFile) != NULL) { str_ltrim(line, "\t\r\n "); //include" "(space) to trim left space str_rtrim(line, "\t\r\n"); //if (!strncmp(ethName, line, strlen(ethName))) if (!strncmp(conf_device, line, strlen(conf_device))) { ethNum += 1; } if (!strncmp(RxBytesName, line, strlen(RxBytesName))) { RxNum += 1; if (ethNum == RxNum && RxNum == 1) { int i = 0; char* p; while ((RxBytes[i] = line[i + strlen(RxBytesName)]) != ' ') { i++; } str_ltrim(RxBytes, " "); str_rtrim(RxBytes, " "); //printf("%s\n", RxBytes); p = strrchr(line, ':'); i = 0; while ((TxBytes[i] = p[i + 1]) != ' ') { i++; } str_ltrim(TxBytes, " "); str_rtrim(TxBytes, " "); //printf("%s\n", TxBytes); //**************************************************** //Get UpdateTime updateTime = time(NULL); //******************************************************* // Read old Rx, Tx data if ((RxTxFile = fopen("/tmp/netBandwidth.dat", "r")) == NULL) { //perror("RxTx.dat"); //exit(1); } else { while (fgets(line, BUFSIZ, RxTxFile) != NULL) { str_ltrim(line, "\t "); str_rtrim(line, "\t\r\n "); if (!strncmp("RX", line, strlen("RX"))) { int i = 0; while (oldRxBytes[i] = line[i + strlen("RX")]) { i++; } //printf("%s\n", oldRxBytes); } if (!strncmp("TX", line, strlen("TX"))) { int i = 0; while (oldTxBytes[i] = line[i + strlen("TX")]) { i++; } //printf("%s\n", oldTxBytes); } if (!strncmp("UT", line, strlen("UT"))) { int i = 0; while (oldUpdateTime[i] = line[i + strlen("UT")]) { i++; } //printf("%s\n", oldUpdateTime); } } fclose(RxTxFile); } //******************************************************* //Write To the RxTx.dat if ((RxTxFile = fopen("/tmp/netBandwidth.dat", "w+")) == NULL) { perror("RxTx.dat"); exit(1); } sprintf(strLine,"RX"); fputs(strLine, RxTxFile); sprintf(strLine, "%s\n", RxBytes); fputs(strLine, RxTxFile); sprintf(strLine, "TX"); fputs(strLine, RxTxFile); sprintf(strLine, "%s\n", TxBytes); fputs(strLine, RxTxFile); sprintf(strLine,"UT"); fputs(strLine, RxTxFile); sprintf(strLine, "%ld\n", updateTime); fputs(strLine, RxTxFile); fclose(RxTxFile); //******************************************************* //Write To the netBandwidthMon.pool if ((poolFile = fopen("../pool/netBandwidthMon.pool", "w+")) == NULL) { perror("netBandwidthMon.pool"); exit(1); } //printf("%s",RxBytes); //printf("%s\n",oldRxBytes); //unsigned long temp =atoll(RxBytes); //printf("%u\n",temp); dataCount = atoll(RxBytes)-atoll(oldRxBytes); //printf("%u\n",dataCount); sprintf(strLine,"%ld\n",updateTime); //printf("%ld\n",updateTime); //printf("%d\n",atoi(strLine)-atoi(oldUpdateTime)); timeCount = atoi(strLine)-atoi(oldUpdateTime); if(timeCount > 0) { inBandSpeed = dataCount / timeCount / 1024; } else { inBandSpeed = 0; } //printf("%f\n", inBandSpeed); dataCount = atoll(TxBytes)-atoll(oldTxBytes); if(timeCount > 0) { outBandSpeed = dataCount / timeCount / 1024; } else { outBandSpeed = 0; } sprintf(strLine, "%.2f\n", inBandSpeed); fputs(strLine, poolFile); sprintf(strLine, "%.2f\n", outBandSpeed); fputs(strLine, poolFile); sprintf(strLine, "%ld\n", updateTime); fputs(strLine, poolFile); fclose(poolFile); }//if (ethNum == RxNum) } } // exit(0); } }
/* return NULL if error */ nutscan_device_t * nutscan_scan_usb() { int ret; char string[256]; char *driver_name = NULL; char *serialnumber = NULL; char *device_name = NULL; char *vendor_name = NULL; struct usb_device *dev; struct usb_bus *bus; usb_dev_handle *udev; nutscan_device_t * nut_dev = NULL; nutscan_device_t * current_nut_dev = NULL; if( !nutscan_avail_usb ) { return NULL; } /* libusb base init */ (*nut_usb_init)(); (*nut_usb_find_busses)(); (*nut_usb_find_devices)(); for (bus = (*nut_usb_busses); bus; bus = bus->next) { for (dev = bus->devices; dev; dev = dev->next) { if ((driver_name = is_usb_device_supported(usb_device_table, dev->descriptor.idVendor, dev->descriptor.idProduct)) != NULL) { /* open the device */ udev = (*nut_usb_open)(dev); if (!udev) { fprintf(stderr,"Failed to open device, \ skipping. (%s)\n", (*nut_usb_strerror)()); continue; } /* get serial number */ if (dev->descriptor.iSerialNumber) { ret = (*nut_usb_get_string_simple)(udev, dev->descriptor.iSerialNumber, string, sizeof(string)); if (ret > 0) { serialnumber = strdup(str_rtrim(string, ' ')); } } /* get product name */ if (dev->descriptor.iProduct) { ret = (*nut_usb_get_string_simple)(udev, dev->descriptor.iProduct, string, sizeof(string)); if (ret > 0) { device_name = strdup(str_rtrim(string, ' ')); } } /* get vendor name */ if (dev->descriptor.iManufacturer) { ret = (*nut_usb_get_string_simple)(udev, dev->descriptor.iManufacturer, string, sizeof(string)); if (ret > 0) { vendor_name = strdup(str_rtrim(string, ' ')); } } nut_dev = nutscan_new_device(); if(nut_dev == NULL) { fprintf(stderr,"Memory allocation \ error\n"); nutscan_free_device(current_nut_dev); free(serialnumber); free(device_name); free(vendor_name); return NULL; } nut_dev->type = TYPE_USB; if(driver_name) { nut_dev->driver = strdup(driver_name); } nut_dev->port = strdup("auto"); sprintf(string,"%04X",dev->descriptor.idVendor); nutscan_add_option_to_device(nut_dev,"vendorid", string); sprintf(string,"%04X", dev->descriptor.idProduct); nutscan_add_option_to_device(nut_dev,"productid", string); if(device_name) { nutscan_add_option_to_device(nut_dev, "product", device_name); free(device_name); device_name = NULL; } if(serialnumber) { nutscan_add_option_to_device(nut_dev, "serial", serialnumber); free(serialnumber); serialnumber = NULL; } if(vendor_name) { nutscan_add_option_to_device(nut_dev, "vendor", vendor_name); free(vendor_name); vendor_name = NULL; } nutscan_add_option_to_device(nut_dev,"bus", bus->dirname); current_nut_dev = nutscan_add_device_to_device( current_nut_dev, nut_dev); memset (string, 0, sizeof(string)); (*nut_usb_close)(udev); }
CHAR* str_trim(register CHAR* s) { s = str_ltrim(s); return str_rtrim(s); }
/** * Removes leading and trailing characters from the specified character string * * @param str * [IN/OUT] string for processing * @param charlist * [IN] null terminated list of characters */ void str_lrtrim(char *str, const char *charlist) { str_rtrim(str, charlist); str_ltrim(str, charlist); }
int test_file(FILE *fp, int argc, char **argv) { char buf[65535 + 1]; char *pos; unsigned int strategy = 0; /* what bucketing strategy we're using */ void *ptr = NULL; unsigned int bucketsize = 0; struct params params = {0}; struct chash *hash = NULL; char name[256]; if (!parse_params(argc, argv, ¶ms)) { fprintf(stderr, "failed to parse params\n"); return 0; } while (fgets((char *) buf, 65535, fp)) { str_rtrim(buf); pos = (char *) str_ltrim(buf); if (!str_casecmp(pos, "new")) { /* creating a new bucket */ unsigned int size = -1; if (ptr) { chash_delete(hash); free(ptr); } /* read parameters */ if ((fscanf(fp, "%255s %u %u", name, &strategy, &size) == 3) && (size <= 65535) && (bucketsize = size) && (ptr = malloc(size)) && (hash = chash_ptr_new(1, 2.0, /* some fn pointer casting dodginess */ (unsigned int (*)(const void *)) str_len, (int (*)(const void *, const void *)) str_cmp)) && (bucket_new(ptr, bucketsize, strategy))) { /* succeeded, do nothing */ if (params.verbose) { printf("%s: new bucket with size %u strategy %u\n", name, size, strategy); } } else { fprintf(stderr, "%s: failed to create bucket\n", name); return 0; } } else if (!str_casecmp(pos, "add")) { /* adding a term to the bucket */ void *ret; unsigned int veclen, succeed, len; int toobig; if (!ptr) { return 0; } /* read parameters */ if ((fscanf(fp, "%65535s %u %u", buf, &veclen, &succeed) == 3) && (veclen <= 65535)) { len = str_len(buf); if ((((ret = bucket_alloc(ptr, bucketsize, strategy, buf, len, veclen, &toobig, NULL)) && succeed) || (!ret && !succeed))) { /* do nothing */ if (params.verbose) { printf("%s: added term '%s'\n", name, buf); } } else if (succeed) { fprintf(stderr, "%s: failed to add '%s' to bucket\n", name, buf); return 0; } else if (!succeed) { fprintf(stderr, "%s: add '%s' succeeded but shouldn't " "have\n", name, buf); return 0; } } else { fprintf(stderr, "%s: failed to add\n", name); return 0; } } else if (!str_casecmp(pos, "ls")) { /* matching stuff in the bucket */ unsigned int numterms, i, len, veclen, veclen2, state; void *addr; struct chash *tmphash; const char *term; void **tmpptr, *tmp; if (!ptr) { return 0; } if (!(tmphash = chash_ptr_new(1, 2.0, /* some fn pointer casting dodginess */ (unsigned int (*)(const void *)) str_len, (int (*)(const void *, const void *)) str_cmp))) { fprintf(stderr, "%s: failed to init hashtable\n", name); return 0; } /* first, fill hashtable with all terms from bucket */ state = 0; while ((term = bucket_next_term(ptr, bucketsize, strategy, &state, &len, &addr, &veclen))) { if (!((term = str_ndup(term, len)) && (chash_ptr_ptr_insert(tmphash, term, (void*) term) == CHASH_OK))) { fprintf(stderr, "%s: failed to init hashtable\n", name); return 0; } } /* now, take terms from file, comparing them with hashtable * entries */ if (fscanf(fp, "%u", &numterms)) { for (i = 0; i < numterms; i++) { if (fscanf(fp, "%65535s %u ", buf, &veclen)) { if (params.verbose) { printf("%s: ls checking %s\n", name, buf); } if ((addr = bucket_find(ptr, bucketsize, strategy, buf, str_len(buf), &veclen2, NULL)) /* remove it from hashtable */ && chash_ptr_ptr_find(tmphash, buf, &tmpptr) == CHASH_OK && chash_ptr_ptr_remove(tmphash, *tmpptr, &tmp) == CHASH_OK && (free(tmp), 1) && (veclen <= 65535) && (veclen2 == veclen) && fread(buf, veclen, 1, fp) && ((buf[veclen] = '\0'), 1) && (!params.verbose || printf("%s: ls check read '%s'\n", name, buf)) && !memcmp(buf, addr, veclen)) { /* do nothing */ } else { unsigned int j; fprintf(stderr, "%s: ls failed cmp '%s' with '", name, buf); for (j = 0; j < veclen; j++) { putc(((char *) addr)[j], stderr); } fprintf(stderr, "'\n"); return 0; } } else { fprintf(stderr, "%s: ls failed\n", name); return 0; } } if (chash_size(tmphash)) { fprintf(stderr, "%s: ls failed\n", name); return 0; } } else { fprintf(stderr, "%s: ls failed\n", name); return 0; } chash_delete(tmphash); if (params.verbose) { printf("%s: matched all (%u) entries\n", name, numterms); } } else if (!str_casecmp(pos, "set")) { /* setting the vector for a term in the bucket */ unsigned int veclen, reallen; void *addr; if (!ptr) { return 0; } /* read parameters */ if ((fscanf(fp, "%65535s %u ", buf, &veclen) == 2) && (veclen <= 65535)) { addr = bucket_find(ptr, bucketsize, strategy, buf, str_len(buf), &reallen, NULL); if (addr && (reallen == veclen) && fread(addr, 1, veclen, fp)) { /* do nothing */ if (params.verbose) { unsigned int j; printf("%s: set term '%s' to '", name, buf); for (j = 0; j < reallen; j++) { putc(((char *) addr)[j], stdout); } printf("'\n"); } } else { fprintf(stderr, "%s: failed to set!\n", name); return 0; } } else { fprintf(stderr, "%s: failed to set\n", name); return 0; } } else if (!str_casecmp(pos, "realloc")) { /* reallocating a term in the bucket */ unsigned int veclen, succeed; int toobig; if (!ptr) { return 0; } /* read parameters */ if ((fscanf(fp, "%65535s %u %u", buf, &veclen, &succeed) == 3) && (veclen <= 65535)) { if (!bucket_realloc(ptr, bucketsize, strategy, buf, str_len(buf), veclen, &toobig)) { fprintf(stderr, "%s: failed to realloc!\n", name); return 0; } } else { fprintf(stderr, "%s: failed to realloc\n", name); return 0; } if (params.verbose) { printf("%s: realloc'd term '%s'\n", name, buf); } } else if (!str_casecmp(pos, "rm")) { /* removing something from the bucket */ unsigned int succeed; if (!ptr) { return 0; } if (fscanf(fp, "%65535s %u", buf, &succeed) == 2) { if (succeed) { if (!(bucket_remove(ptr, bucketsize, strategy, buf, str_len(buf)))) { fprintf(stderr, "%s: failed to rm '%s'\n", name, buf); return 0; } else if (params.verbose) { printf("%s: rm term '%s'\n", name, buf); } } else if (succeed) { fprintf(stderr, "%s: failed to rm\n", name); return 0; } } else { fprintf(stderr, "%s: failed to rm\n", name); return 0; } } else if (!str_casecmp(pos, "print")) { /* printing out the bucket contents */ unsigned int state = 0, len, veclen; const char *term; char format[100]; void *addr; if (!ptr) { printf("can't print, no bucket\n"); } else { do { term = bucket_next_term(ptr, bucketsize, strategy, &state, &len, &addr, &veclen); } while (term && memcpy(buf, term, len) && ((buf[len] = '\0') || 1) && snprintf(format, 100, "%%.%us (%%u): '%%.%us' (%%u) " "(off %%u)\n", len, veclen) && printf(format, term, len, (char*) addr, veclen, ((char *) addr) - (char *) ptr)); if (!state) { printf("(empty)\n"); } printf("%u entries, %u data, %u string, %u overhead, %u free\n", bucket_entries(ptr, bucketsize, strategy), bucket_utilised(ptr, bucketsize, strategy), bucket_string(ptr, bucketsize, strategy), bucket_overhead(ptr, bucketsize, strategy), bucket_unused(ptr, bucketsize, strategy)); } } else if (!str_casecmp(pos, "match")) { unsigned int veclen, veclen2; void *addr; if (fscanf(fp, "%65535s %u ", buf, &veclen)) { if ((addr = bucket_find(ptr, bucketsize, strategy, buf, str_len(buf), &veclen2, NULL)) && (veclen <= 65535) && (veclen2 >= veclen) && (!params.verbose || printf("%s: match on '%s' ", name, buf)) && fread(buf, veclen, 1, fp) && !memcmp(buf, addr, veclen)) { if (params.verbose) { printf("content succeeded\n"); } } else { fprintf(stderr, "%s: match failed (%s vs %s)\n", name, buf, (char *) addr); return 0; } } else { fprintf(stderr, "%s: match failed\n", name); return 0; } } else if ((*pos != '#') && str_len(pos)) { fprintf(stderr, "%s: unknown command '%s'\n", name, pos); return 0; } } if (ptr) { chash_delete(hash); free(ptr); } return 1; }
int main() { char buf[BUFSIZ + 1]; struct queryparse *qp; int ret; char word[100]; unsigned int len, warn; while (fgets(buf, BUFSIZ, stdin)) { str_rtrim(buf); printf("query: %s\n", buf); if (!(qp = queryparse_new(50, buf, str_len(buf)))) { fprintf(stderr, "couldn't initialise parser\n"); return EXIT_FAILURE; } do { ret = queryparse_parse(qp, word, &len); warn = queryparse_warn(qp); switch (ret) { case QUERYPARSE_ERR: fprintf(stderr, "queryparse got error %d %s\n", queryparse_err(qp), strerror(queryparse_err(qp))); ret = QUERYPARSE_EOF; break; case QUERYPARSE_WORD: assert(len == str_len(word)); printf("WORD: %s\n", word); break; case QUERYPARSE_WORD_NOSTOP: assert(len == str_len(word)); printf("WORD_NS: %s\n", word); break; case QUERYPARSE_WORD_EXCLUDE: assert(len == str_len(word)); printf("WORD_EX: %s\n", word); break; case QUERYPARSE_OR: printf("OR\n"); break; case QUERYPARSE_AND: printf("AND\n"); break; case QUERYPARSE_START_PHRASE: printf("PHRASE \"\n"); break; case QUERYPARSE_END_PHRASE: printf("\" PHRASE\n"); break; case QUERYPARSE_START_MODIFIER: assert(len == str_len(word)); printf("MOD %s [\n", word); break; case QUERYPARSE_END_MODIFIER: printf("] MOD \n"); break; case QUERYPARSE_END_SENTENCE: printf("ENDSENT\n"); break; case QUERYPARSE_EOF: break; default: fprintf(stderr, "unexpected output!\n"); ret = QUERYPARSE_EOF; break; } while (warn) { printf("%s\n", warn_mesg(&warn)); } } while ((ret != QUERYPARSE_EOF)); queryparse_delete(qp); } return EXIT_SUCCESS; }
char *str_trim(char *string, const char character) { return str_rtrim(str_ltrim(string, character), character); }
/* * strim, karakter dizisinin sagindaki ve solundaki * bosluklari kaldirir. * * @param s : karakter dizisi */ char *strim(char *s){ return str_ltrim(str_rtrim(s)); }
static int64_t do_copy(const char *src, const char *dest, size_t blen, int vb, int recursive, int force, int interactive) { int r = -1; char dest_path[PATH_MAX]; char src_path[PATH_MAX]; DIR *dir = NULL; struct dirent *dp; dentry_type_t src_type = get_type(src); dentry_type_t dest_type = get_type(dest); const size_t src_len = str_size(src); if (src_type == TYPE_FILE) { char *src_fname; /* Initialize the src_path with the src argument */ str_cpy(src_path, src_len + 1, src); str_rtrim(src_path, '/'); /* Get the last component name from the src path */ src_fname = get_last_path_component(src_path); /* Initialize dest_path with the dest argument */ str_cpy(dest_path, PATH_MAX, dest); if (dest_type == TYPE_DIR) { /* e.g. cp file_name /data */ /* e.g. cp file_name /data/ */ /* dest is a directory, * append the src filename to it. */ merge_paths(dest_path, PATH_MAX, src_fname); dest_type = get_type(dest_path); } else if (dest_type == TYPE_NONE) { if (dest_path[str_size(dest_path) - 1] == '/') { /* e.g. cp /textdemo /data/dirnotexists/ */ printf("The dest directory %s does not exists", dest_path); goto exit; } } if (dest_type == TYPE_DIR) { printf("Cannot overwrite existing directory %s\n", dest_path); goto exit; } else if (dest_type == TYPE_FILE) { /* e.g. cp file_name existing_file */ /* dest already exists, * if force is set we will try to remove it. * if interactive is set user input is required. */ if (force && !interactive) { if (unlink(dest_path) != 0) { printf("Unable to remove %s\n", dest_path); goto exit; } } else if (!force && interactive) { bool overwrite = get_user_decision(false, "File already exists: %s. Overwrite? [y/N]: ", dest_path); if (overwrite) { printf("Overwriting file: %s\n", dest_path); if (unlink(dest_path) != 0) { printf("Unable to remove %s\n", dest_path); goto exit; } } else { printf("Not overwriting file: %s\n", dest_path); r = 0; goto exit; } } else { printf("File already exists: %s\n", dest_path); goto exit; } } /* call copy_file and exit */ r = (copy_file(src, dest_path, blen, vb) < 0); } else if (src_type == TYPE_DIR) { /* e.g. cp -r /x/srcdir /y/destdir/ */ if (!recursive) { printf("Cannot copy the %s directory without the " "-r option\n", src); goto exit; } else if (dest_type == TYPE_FILE) { printf("Cannot overwrite a file with a directory\n"); goto exit; } char *src_dirname; /* Initialize src_path with the content of src */ str_cpy(src_path, src_len + 1, src); str_rtrim(src_path, '/'); src_dirname = get_last_path_component(src_path); str_cpy(dest_path, PATH_MAX, dest); switch (dest_type) { case TYPE_DIR: if (str_cmp(src_dirname, "..") && str_cmp(src_dirname, ".")) { /* The last component of src_path is * not '.' or '..' */ merge_paths(dest_path, PATH_MAX, src_dirname); if (mkdir(dest_path, 0) != 0) { printf("Unable to create " "dest directory %s\n", dest_path); goto exit; } } break; default: case TYPE_NONE: /* dest does not exists, this means the user wants * to specify the name of the destination directory * * e.g. cp -r /src /data/new_dir_src */ if (mkdir(dest_path, 0) != 0) { printf("Unable to create " "dest directory %s\n", dest_path); goto exit; } break; } dir = opendir(src); if (!dir) { /* Something strange is happening... */ printf("Unable to open src %s directory\n", src); goto exit; } /* Copy every single directory entry of src into the * destination directory. */ while ((dp = readdir(dir))) { struct stat src_s; struct stat dest_s; char src_dent[PATH_MAX]; char dest_dent[PATH_MAX]; str_cpy(src_dent, PATH_MAX, src); merge_paths(src_dent, PATH_MAX, dp->d_name); str_cpy(dest_dent, PATH_MAX, dest_path); merge_paths(dest_dent, PATH_MAX, dp->d_name); /* Check if we are copying a directory into itself */ stat(src_dent, &src_s); stat(dest_path, &dest_s); if (dest_s.index == src_s.index && dest_s.fs_handle == src_s.fs_handle) { printf("Cannot copy a directory " "into itself\n"); goto exit; } if (vb) printf("copy %s %s\n", src_dent, dest_dent); /* Recursively call do_copy() */ r = do_copy(src_dent, dest_dent, blen, vb, recursive, force, interactive); if (r) goto exit; } } else printf("Unable to open source file %s\n", src); exit: if (dir) closedir(dir); return r; }
int str_trim(char* str) { str_ltrim(str); str_rtrim(str); return 0; }
void test_css_util_other() { char str[24]; char test[10]; char* s = NULL; char* t = NULL; assert(strcmp("922337203685477587",lltoa(922337203685477587,str,10)) == 0); strcpy(test," abc"); str_trim(test); assert( 0 == strcmp(test,"abc")); strcpy(test," abc "); str_trim(test); assert( 0 == strcmp(test,"abc")); strcpy(test,"abc "); str_trim(test); assert( 0 == strcmp(test,"abc")); strcpy(test," a b c "); str_trim(test); assert( 0 == strcmp(test,"a b c")); strcpy(test," "); str_trim(test); assert( 0 == strcmp(test,"")); strcpy(test," abc"); str_ltrim(test); assert( 0 == strcmp(test,"abc")); strcpy(test," abc "); str_rtrim(test); assert( 0 == strcmp(test," abc")); strcpy(test," abc "); str_ltrim(test); assert( 0 == strcmp(test,"abc ")); strcpy(test," a b c "); str_ltrim(test); assert( 0 == strcmp(test,"a b c ")); strcpy(test," "); str_ltrim(test); assert( 0 == strcmp(test,"")); strcpy(test," "); str_rtrim(test); assert( 0 == strcmp(test,"")); memset(test,' ',10); strcpy(test,"a=b"); get_split_str(test,"=",1,&s); assert( 0 == strcmp(s,"b")); FREE(s); get_split_str(test,"=",0,&s); assert( 0 == strcmp(s,"a")); FREE(s); get_split_strs(test,"=",&s,&t); assert( 0 == strcmp(s,"a")); assert( 0 == strcmp(t,"b")); FREE(s); FREE(t); memset(test,' ',10); strcpy(test," a = b "); get_split_str(test,"=",1,&s); str_trim(s); assert( 0 == strcmp(s,"b")); FREE(s); get_split_str(test,"=",0,&s); str_trim(s); assert( 0 == strcmp(s,"a")); FREE(s); get_split_strs(test,"=",&s,&t); str_trim(s); str_trim(t); assert( 0 == strcmp(s,"a")); assert( 0 == strcmp(t,"b")); FREE(s); FREE(t); assert(0 == ensure_dir("./test/dir")); assert(0 == ensure_dir("./test/dir/")); }
char * str_trim(char *str) { char *ptr; ptr = str_rtrim(str); str = str_ltrim(ptr); return str; }
void str_trim(char *str) { str_rtrim(str); str_ltrim(str); }