static void join (string cp) { char temp[BUFSIZ], *tp; if (!fgets (temp, BUFSIZ, stdin)) return; remove_newline (temp); *cp++ = ' '; for (tp = temp; *tp == ' '; ++tp) ; strcpy (cp, tp); }
int load_numbers(const char *filename, intmax_t **ret, size_t *ret_len) { char *line = NULL; char *endptr = NULL; size_t len = 0; ssize_t read = 0; intmax_t *array = malloc(sizeof *array); size_t arr_len = 0; size_t arr_alloc = 1; int ret_val = 0; FILE *fp = fopen(filename, "r"); if (fp == NULL) { perror(filename); return -1; } while ((read = getline(&line, &len, fp)) != -1) { if (arr_len == arr_alloc) { arr_alloc *= 2; intmax_t *tmp = realloc(array, sizeof *array * arr_alloc); if (tmp) { array = tmp; } else { perror("realloc"); ret_val = -1; break; } } array[arr_len++] = strtoimax(line, &endptr, 10); if (*endptr && *endptr != '\n') { remove_newline(line); fprintf(stderr, "\"%s\" is not a valid integer\n", line); ret_val = -1; break; } } fclose(fp); if (line) { free(line); } if (ret) { *ret = array; } if (ret_len) { *ret_len = arr_len; } return ret_val; }
int reverse_file(char* file_path, int simul_count){ int i = 0; FILE *fp = fopen(file_path, "r"); char* line = 0; StrWordRev* lines[simul_count]; size_t len = 0; ssize_t read; while(1){ // Get `simul_count` number of strings from files, turning them into SWR structs. for (i = 0; i < simul_count; ++i){ read = getline(&line, &len, fp); if (read == -1){ fclose(fp); return 1; } remove_newline(line); lines[i] = new_swr(line); free(line); line = 0; } while (!all_complete(lines, simul_count)){ // Move the cursor to the "top" of the block for (i = 0; i < simul_count; ++i){ printf("\033[1A"); printf("\033[1A"); printf("\r"); } // Conduct a single "tick" of the reversal of each string for (i = 0; i < simul_count; ++i){ if (lines[i]->state != COMPLETE){ tick_reverse_word(lines[i]); } // Print each string with it's fancy highlighting rev_debug_print(lines[i]->raw_str, lines[i]->a, lines[i]->b); } usleep(50000); } for (i = 0; i < simul_count; ++i){ rev_debug_print(lines[i]->raw_str, lines[i]->a, lines[i]->b); } } fclose(fp); return 0; }
int main() { char line[100]; items.reserve(1000); while(std::fgets(line, sizeof(line), stdin)) { items.clear(); idx.clear(); inst_list.clear(); while(line[0] != 'E') { remove_newline(line); process_cmd(line); std::fgets(line, sizeof(line), stdin); } std::puts("END"); } return 0; }
int main(void) { char test1[]="12345"; char test2[]="12345"; char test3[]="kkk12345"; char *test4=0; char test5[32]; printf("test for 12345 v1 is %ld, test for 12345 v2 is %ld, test for kkk12345 %ld ," "test for null ptr is %ld\n", atol(test1), atol(test2), atol(test3), atol(test4)); while (fgets(test5, 512, stdin)) { printf("input is %s sizeof test5 %lu, strlen is %zd num is %ld\n", remove_newline(test5), sizeof(test5),strlen(test5), atol(test5)); } }
/* line-split `data'. Initially `*buffer' should contain NULL. */ int line_split(const char *data, int len, char **output, LINEBUF_REC **buffer) { LINEBUF_REC *rec; int ret; g_return_val_if_fail(data != NULL, -1); g_return_val_if_fail(output != NULL, -1); g_return_val_if_fail(buffer != NULL, -1); if (*buffer == NULL) *buffer = g_new0(LINEBUF_REC, 1); rec = *buffer; if (rec->remove > 0) { rec->len -= rec->remove; g_memmove(rec->str, rec->str+rec->remove, rec->len); rec->remove = 0; } if (len > 0) linebuf_append(rec, data, len); else if (len < 0) { /* connection closed.. */ if (rec->len == 0) return -1; /* no new data got but still something in buffer.. */ len = 0; if (linebuf_find(rec, '\n') == NULL) { /* connection closed and last line is missing \n .. just add it so we can see if it had anything useful.. */ linebuf_append(rec, "\n", 1); } } ret = remove_newline(rec); *output = rec->str; return ret; }
/** Prüfen ob ein E-Mail in der Datenbank existiert. - für Registrierungsformular - Javascript führt Anfrage aus --> Auswertung der Antwort im Browser --> dem Benutzer wir eine Warnung angezeigt, wenn die E-Mail schon in der DB existiert. */ int main(int argc, char ** argv){ cgi thisCGI; init_CGI(&thisCGI); get_CGI_data(&thisCGI); char * email=NULL; extract_POST_data(&thisCGI, "email", &email); remove_newline(email); httpHeader(TEXT); if(email_exists(email)){ puts("exists\n"); }else{ puts("no\n"); } printf("Email war: '%s'\n", email); return 1; }
/**************************************************************************** * * Function Name : main * Description : Demonstration basic string concepts * Returns : Success or Failure * ****************************************************************************/ int main() { char input[NAMESZ]; /* Variable to get input from user */ char reverse[NAMESZ]; /* Variable to store reverse of string */ char *fgets_ret = NULL; /* Return Value from fgets */ /* Initializing the local variables */ memset(input, 0, NAMESZ); memset(reverse, 0, NAMESZ); printf("Enter a string (Size < 32)\n"); /* Observe the waring given by compiler for the following line. Compiler gives the warning since there is no array bound check for gets */ /* Same issue is there with scanf also */ // gets(input); /* fgets has an option to specify the array bound */ fgets_ret = fgets(input, NAMESZ,stdin); if(NULL != fgets_ret) { /* fgets reads a maximum of NAMESZ-1 characters. Last position is reserved for '\0'. But there could be a '\n' before '\0' if the number of characters were less than NAMESZ-1. So we need to remove it */ remove_newline(input); /* reversing the string */ str_rev(input, reverse); printf("Original string is %s\n", input); printf("Original string is %s\n", reverse); /* Checking for palindrome */ palindrome_check(input,reverse); } else { printf("fgets failed\n"); } return 0; }
void read_input(struct info *inf, char* workload) { char * line = NULL; size_t len = 0; ssize_t read; FILE *fp = fopen(workload, "r"); if (fp == NULL) exit(EXIT_FAILURE); while ((read = getline(&line, &len, fp)) != -1) { if (read == 1 || line[0] == '\0') break; if (inf->count >= inf->num_elements) { inf->num_elements += 10; inf->msg = realloc(inf->msg, inf->num_elements); } remove_newline(line); inf->msg[inf->count] = strdup(line); inf->count++; } if (line) free(line); fclose(fp); }
int main(int argc, char ** argv) { check(); // Передан файл базы как параметр if (argc == 2) { db_filename = argv[1]; } // Файл не передан, используется имя по умолчанию else if (argc == 1) { db_filename = "default.db"; } // Неправильное использование else { fprintf( stderr, "Usage: dictionary [words.db]\n"); exit( EXIT_WRONG_USAGE); } assert(NULL != db_filename); FILE * f = NULL; int code = access(db_filename, R_OK | W_OK); // Нет прав, не существует файл или что-нибудь ещё if (-1 == code) { // Нет файла, можно создавать if ( errno == ENOENT) { f = fopen(db_filename, "w+"); fprintf( stderr, "INFO: Файл не существовал и теперь создан.\n"); } else if ( errno == EACCES) { fprintf( stderr, "FATAL: Нет прав доступа к базе.\n"); exit( EXIT_WRONG_RIGHTS); } else { printf("errno = %d\n", errno); exit( EXIT_WTF); } } // Есть права и файл существует else { f = fopen(db_filename, "r+"); fprintf( stderr, "INFO: Существующий файл открыт для работы.\n"); } assert(NULL != f); fseek(f, 0, SEEK_END); int length = ftell(f); fprintf( stderr, "DEBUG: Длина файла: %d\n", length); if (length < HEADER_SIZE) { // Длина файла заведомо меньше размера header. Пишем новый. write_new_header(&header, f); } else { // Читаем read_header(&header, f); // Проверяем if (header.version != 1 || header.actual_words > header.total_words) { fprintf( stderr, "FATAL: База данных (%s), вероятно, испорчена. Возможно, стоит её удалить.\n", db_filename); WTF(); } } // Всё есть. Можно работать. printf("Введите help для справки, quit для выхода.\n"); int working = 1; while (working) { printf("> "); char str[6]; fgets(str, 6, stdin); remove_newline(str); if (strcmp(str, "help") == 0) { command_help(); } else if (strcmp(str, "quit") == 0 || strcmp(str, "exit") == 0 || strcmp(str, "bye") == 0) { save_database(f); exit( EXIT_SUCCESS); } else if (strcmp(str, "add") == 0) { command_add(f); } else if (strcmp(str, "find") == 0) { command_find(f); } else if (strcmp(str, "del") == 0 || strcmp(str, "rm") == 0) { command_remove(f); } else if (strcmp(str, "frag") == 0) { command_defragment(f); } else { fprintf( stderr, "ERROR: Неизвестная команда '%s'\n", str); } } /* Операции: 1. Добавить слово. Имя (128 байт), содержание (не ограничено) -> 2. Найти слово. Имя -> содержание 3. Удалить. Имя -> */ if (f != NULL) fclose(f); return EXIT_SUCCESS; }
int main P2C(int, argc, string *, argv) { register char *cp; int blanks_done, indent, i; char *program_name = ""; kpse_set_program_name (argv[0], NULL); /* In case we use FATAL. */ for (i = 1; i < argc; i++) { if (STREQ(argv[i],"-t")) tex = true; else program_name = argv[i]; } while (fgets (buf, BUFSIZ, stdin)) { remove_newline (buf); blanks_done = false; for (cp = buf; *cp; ++cp) ; while (cp != buf && *--cp == ' ') ; while (*cp == '.') { join (cp + 1); while (*cp) ++cp; while (*--cp == ' ') ; } for (cp = buf, indent = 0; *cp == ' ' || *cp == '\t'; ++cp) { if (*cp == ' ') indent++; else indent += 8; } if (!*cp) { /* All blanks, possibly with "{" */ puts (buf); continue; } if (*cp == '{') { do_blanks (indent); putchar ('{'); ++cp; while (*cp == ' ' || *cp == '\t') ++cp; blanks_done = true; if (!*cp) { putchar ('\n'); continue; } } if (!blanks_done) do_blanks (indent); if (strncmp (cp, "read ( input", 12) == 0) { char variable_name[20]; if (sscanf (cp, "read ( input , %s )", variable_name) != 1) { fprintf (stderr, "sscanf failed\n"); uexit (1); } printf ("%s = getint();\n", variable_name); continue; } if (strncmp (cp, "lab", 3) == 0 && strchr (cp, ':')) { do { putchar (*cp); } while (*cp++ != ':'); while (*cp == ' ') ++cp; putchar (' '); } if (strncmp (cp, "else write", 10) == 0) { puts ("else"); do_blanks (indent); cp += 5; while (*cp == ' ') ++cp; } if (bare (cp, '{')) { while (*cp != '{') { putchar (*cp); ++cp; } ++cp; puts ("{"); indent += 4; do_blanks (indent); while (*cp == ' ') ++cp; } if (strncmp (cp, "write (", 7) && strncmp (cp, "writeln (", 9)) { /* if not a write/writeln, just copy it to stdout and continue */ puts (cp); continue; } cmd = cp; while (!whole (buf)) /* make sure we have whole stmt */ { fgets (&buf[strlen (buf)], BUFSIZ - strlen (buf), stdin); remove_newline (buf); } while (*cp != '(') ++cp; ++cp; while (*(cp + 1) == ' ') ++cp; /* Some writes start with a variable, instead of a file. */ if (*(cp + 1) == '"' || *(cp + 1) == '\'' || strncmp (cp + 1, "buffer", 6) == 0 || strncmp (cp + 1, "xchr", 4) == 0 || strncmp (cp + 1, "k ,", 3) == 0 || strncmp (cp + 1, "s ,", 3) == 0 || strncmp (cp + 1, "dig", 3) == 0 || strncmp (cp + 1, "HEX", 3) == 0 || strncmp (cp + 1, "versionstring", 13) == 0 || strncmp (cp + 1, "kpathseaversionstring", 21) == 0 ) strcpy (filename, "stdout"); else { file = filename; while (*cp != ',' && *cp != ')') *file++ = *cp++; *file = '\0'; } if (*cp == ')') { printf ("putc%s ('\\n', %s);\n", oem, filename); continue; } argp = ++cp; as = args; while (*cp == ' ') ++cp; while (*cp != ')') { if (*cp == '\'' || strncmp (cp, "xchr", 4) == 0 || (strncmp (cp ,"HEX", 3) == 0 && (STREQ (program_name, "ofm2opl") || STREQ (program_name, "opl2ofm") || STREQ (program_name, "ovp2ovf") || STREQ (program_name, "ovf2ovp"))) || strncmp (cp, "ASCII04", 7) == 0 || strncmp (cp, "ASCII1", 6) == 0 || strncmp (cp, "ASCIIall", 8) == 0 || strncmp (cp, "months", 6) == 0 || strncmp (cp, "nameoffile", 10) == 0 || (strncmp (cp, "buffer", 6) == 0 && (STREQ (program_name, "vptovf") || STREQ (program_name, "pltotf") || STREQ (program_name, "ovp2ovf") || STREQ (program_name, "ofm2opl"))) || (((strncmp (cp, "buf", 3) == 0 || strncmp (cp, "xdig", 4) == 0 || strncmp (cp, "xext", 4) == 0 || strncmp (cp, "xhyf", 4) == 0) && STREQ (program_name, "patgen"))) ) { *as++ = '%'; *as++ = 'c'; if (tex && strncmp (cp, "xchr", 4) == 0) { *cp = 'X'; cp = strchr (cp, '['); *cp = '('; cp = advance_cp(cp,1); *cp++ = ')'; } else if (*cp == '\'') cp += 2; } else if (*cp == '"') { *as++ = '%'; *as++ = 's'; while (*++cp != '"') /* skip to end of string */ if (*cp == '\\') ++cp; /* allow \" in string */ } /* More kludge -- versionstring is a string, not a number, so we have to use %s. */ else if (strncmp (cp, "versionstring", 13) == 0) { *as++ = '%'; *as++ = 's'; } else { *as++ = '%'; *as++ = 'l'; *as++ = 'd'; cp = insert_long (cp); cp = skip_balanced (cp); /* It's a numeric expression */ } while (*cp != ',' && *cp != ')') ++cp; while (*cp == ',' || *cp == ' ') ++cp; } if (strncmp (cmd, "writeln", 7) == 0) { *as++ = '\\'; *as++ = 'n'; } *as = '\0'; if (strcmp (args, "%c") == 0) { for (as = argp; *as; ++as) ; while (*--as != ')') ; *as = '\0'; printf ("putc%s (%s, %s);\n", oem, argp, filename); } else if (STREQ (args, "%s")) printf ("Fputs%s (%s, %s\n", oem, filename, argp); else printf ("fprintf%s (%s, \"%s\", %s\n", oem, filename, args, argp); } return EXIT_SUCCESS; }
Result parsecopy_saveconfig(char *versiondir, u32 type, int selected_slot) { FILE *f, *fsave; int fd=0; int len; int ret = 2; u8 *savebuffer; u32 savesize; char *strptr; char *namestr, *valuestr; u32 tmpval=0; struct stat filestats; char line[256]; char tmpstr[256]; char tmpstr2[256]; char savedir[256]; memset(savedir, 0, sizeof(savedir)); memset(tmpstr, 0, sizeof(tmpstr)); if(type < 2) snprintf(savedir, sizeof(savedir) - 1, "%s/%s", versiondir, type == 0 ? "Old3DS" : "New3DS"); else snprintf(savedir, sizeof(savedir) - 1, "%s/%s", versiondir, "common"); snprintf(tmpstr, sizeof(tmpstr) - 1, "%s/%s", savedir, "config.ini"); f = fopen(tmpstr, "r"); if(f == NULL) return 1; memset(line, 0, sizeof(line)); while(fgets(line, sizeof(line) - 1, f)) { remove_newline(line); len = strlen(line); if(len == 0) continue; strptr = strtok(line, "="); if(strptr == NULL) break; namestr = strptr; strptr = strtok(NULL, "="); if(strptr == NULL) break; valuestr = strptr; memset(tmpstr2, 0, sizeof(tmpstr2)); ret = convert_filepath(namestr, tmpstr2, sizeof(tmpstr2), selected_slot); if(ret) break; memset(tmpstr, 0, sizeof(tmpstr)); snprintf(tmpstr, sizeof(tmpstr) - 1, "%s/%s", savedir, tmpstr2); fsave = fopen(tmpstr, "r"); if(fsave == NULL) { ret = 3; break; } fd = fileno(fsave); if(fd == -1) { fclose(fsave); ret = errno; break; } if(fstat(fd, &filestats) == -1) { fclose(fsave); ret = errno; break; } savesize = filestats.st_size; if(savesize == 0) { fclose(fsave); ret = 4; break; } savebuffer = malloc(savesize); if(savebuffer == NULL) { fclose(fsave); ret = 5; break; } tmpval = fread(savebuffer, 1, savesize, fsave); fclose(fsave); if(tmpval != savesize) { ret = 6; free(savebuffer); break; } memset(tmpstr2, 0, sizeof(tmpstr2)); ret = convert_filepath(valuestr, tmpstr2, sizeof(tmpstr2), selected_slot); if(ret) { free(savebuffer); break; } ret = write_savedata(tmpstr2, savebuffer, savesize); free(savebuffer); if(ret) break; } fclose(f); return ret; }
Result load_exploitconfig(char *exploitname, u64 *cur_programid, u32 app_remaster_version, u16 *update_titleversion, u32 *installed_remaster_version, char *out_versiondir, char *out_displayversion) { FILE *f; int len; int ret = 2; int stage = 0; unsigned int tmpver, tmpremaster; char *strptr; char *namestr = NULL, *valuestr = NULL; char filepath[256]; char line[256]; if(update_titleversion == NULL) { *installed_remaster_version = app_remaster_version; stage = 2; ret = 5; } memset(filepath, 0, sizeof(filepath)); snprintf(filepath, sizeof(filepath) - 1, "romfs:/%s/%016llx/config.ini", exploitname, *cur_programid); f = fopen(filepath, "r"); if(f == NULL) return 1; memset(line, 0, sizeof(line)); while(fgets(line, sizeof(line) - 1, f)) { remove_newline(line); len = strlen(line); if(len == 0) continue; if(stage == 1 || stage == 3) { strptr = strtok(line, "="); if(strptr == NULL) continue; namestr = strptr; strptr = strtok(NULL, "="); if(strptr == NULL) continue; valuestr = strptr; } if(stage == 0) { if(strcmp(line, "[updatetitle_versions]") == 0) { ret = 3; stage = 1; } } else if(stage == 1) { tmpver = 0; tmpremaster = 0; if(sscanf(namestr, "v%u", &tmpver) == 1) { if(sscanf(valuestr, "%04X", &tmpremaster) == 1) { if(tmpver == *update_titleversion) { if(app_remaster_version < tmpremaster) { *installed_remaster_version = tmpremaster; } else { *installed_remaster_version = app_remaster_version; } ret = 4; stage = 2; fseek(f, 0, SEEK_SET); } } } } else if(stage == 2) { if(strcmp(line, "[remaster_versions]") == 0) { ret = 5; stage = 3; } } else if(stage == 3) { tmpremaster = 0; if(sscanf(namestr, "%04X", &tmpremaster) == 1) { if(*installed_remaster_version == tmpremaster) { ret = 4; strptr = strtok(valuestr, "@"); if(strptr == NULL) break; strncpy(out_versiondir, strptr, 63); strptr = strtok(NULL, "@"); if(strptr == NULL) break; strncpy(out_displayversion, strptr, 63); ret = 0; break; } } } } fclose(f); return ret; }
Result load_exploitversion(char *exploitname, u64 *cur_programid, int index, u32* out_remaster, char* out_displayversion) { int ret = 2; int len; char *strptr; char *namestr = NULL, *valuestr = NULL; char filepath[256] = {0}; char line[256] = {0}; snprintf(filepath, sizeof(filepath) - 1, "romfs:/%s/%016llx/config.ini", exploitname, *cur_programid); int stage = 0; int i = 0; FILE* f = fopen(filepath, "r"); if(f == NULL) return 1; while(fgets(line, sizeof(line) - 1, f)) { remove_newline(line); len = strlen(line); if(len == 0) continue; if(stage == 0) { if(strcmp(line, "[remaster_versions]") == 0) { ret = 3; stage = 1; } } else if(stage == 1) { if(i != index) { i++; continue; } strptr = strtok(line, "="); if(strptr == NULL) continue; namestr = strptr; strptr = strtok(NULL, "="); if(strptr == NULL) continue; valuestr = strptr; unsigned int tmpremaster = 0; if(sscanf(namestr, "%04X", &tmpremaster) == 1) { ret = 4; strptr = strtok(valuestr, "@"); if(strptr == NULL) break; strptr = strtok(NULL, "@"); if(strptr == NULL) break; if(out_displayversion) strncpy(out_displayversion, strptr, 63); if(out_remaster) *out_remaster = tmpremaster; ret = 0; break; } } } fclose(f); return ret; }
int main P1H(void) { register int i; #ifdef vax register char *cp; #endif for (i=0; i<NUMTYPES; i++) lens[i] = strlen(types[i]); /* Copy the declarations. */ while (fgets (line, BUFFER_SIZE, stdin) && strncmp (&line[10], "coerce", 6) != 0) { remove_newline (line); puts (line); } puts (line); while (fgets (line, BUFFER_SIZE, stdin)) { remove_newline (line); #ifdef vax if (cp = matchestype() ) { Puts(" register long "); puts(cp); #else if ( matchestype() ) { Puts(" register"); puts(line+1); #endif } else puts(line); } fclose (stdout); uexit (0); } #else /* not REGFIX */ /* If we don't want to use register variables, we just copy stdin to stdout. If writing or reading fail, exit with bad status. */ int main () { int c; while ((c = getchar ()) != EOF) { if (putchar (c) == EOF) { perror ("regfix"); exit (EXIT_FAILURE); } } if (!feof (stdin)) { perror ("regfix"); exit (EXIT_FAILURE); } return EXIT_SUCCESS; }
int main (int argc, char **argv) { struct arguments arguments; // Set up variables int num_columns; int num_rows; // multithreading params thread_args t_args[NUM_THREADS]; pthread_t thread_id[NUM_THREADS]; int ind_per_thread; int start_index; int stop_index; size_t i,j,k,m; // Initialize NETCDF Variables int ncid, row_dimid, col_dimid; int varid; int retval; char FILE_NAME[100]; int dimids[NDIMS]; /* Default values. */ arguments.verbose = 0; arguments.region = NULL; /* Parse our arguments; every option seen by parse_opt will be reflected in arguments. */ argp_parse (&argp, argc, argv, 0, 0, &arguments); char* region = arguments.region; printf ("GEN_WARP_IMAGES\n---------------\nBeginning processing with options:\n"); printf ("Region = %s\nVERBOSE = %s\n---------------\n", arguments.region, arguments.verbose ? "yes" : "no"); // define image areas based on region if (strcmp(region,"Ama") == 0) { num_columns = 1128; num_rows = 744; } else if (strcmp(region,"Ber") == 0) { num_columns = 1350; num_rows = 750; } else if (strcmp(region,"CAm") == 0) { num_columns = 1440; num_rows = 700; } else if (strcmp(region,"ChJ") == 0) { num_columns = 1980; num_rows = 950; } else if (strcmp(region,"Eur") == 0) { num_columns = 1530; num_rows = 1040; } else if (strcmp(region,"Ind") == 0) { num_columns = 1800; num_rows = 680; } else if (strcmp(region,"NAf") == 0) { num_columns = 2120; num_rows = 1130; } else if (strcmp(region,"NAm") == 0) { num_columns = 1890; num_rows = 1150; } else if (strcmp(region,"SAf") == 0) { num_columns = 1220; num_rows = 1260; } else if (strcmp(region,"SAm") == 0) { num_columns = 1310; num_rows = 1850; } else if (strcmp(region,"SAs") == 0) { num_columns = 1760; num_rows = 720; } else { printf("ERROR SETTING REGION SIZES!"); exit(-1); } // open example sir file sir_head head; char sir_fname[150]; sprintf(sir_fname,"/home/lindell/workspace/soil_moisture/sm_gen_warp_images/sir/%s.sir",region); FILE *sir_fid = fopen(sir_fname,"r"); if (sir_fid == NULL) { fprintf(stderr,"*** could not open list file %s\n",sir_fname); exit(-1); } get_sir_head_file(sir_fid,&head); head.ascale = head.ascale/2.809; head.bscale = head.bscale/2.809; // printf("NUM_ROWS: %d\nNUM_COL: %d\nNUM_DAYS: %d\nNUM_YEARS: %d\nREG:%s\n",num_rows,num_columns,NUM_DAYS,NUM_YEARS,region); // exit(-1); // Allocate memory for 4D image timeseries array setvbuf (stdout, NULL, _IONBF, 0); printf("Allocating Memory..."); float ****row_ptr = (float****)malloc(sizeof(float ***)*num_rows); float ***column_ptr = (float***)malloc(sizeof(float **)*num_rows * num_columns); float **day_ptr = (float**)malloc(sizeof(float *)*num_rows * num_columns*NUM_DAYS); float *year_ptr = (float*)malloc(sizeof(float)*num_rows*num_columns*NUM_YEARS*NUM_DAYS); float ****storage = row_ptr; for (i = 0; i < num_rows; i++, column_ptr += num_columns) { storage[i] = column_ptr; for (j = 0; j < num_columns; j++, day_ptr += NUM_DAYS) { storage[i][j] = day_ptr; for (k = 0; k < NUM_DAYS; k++, year_ptr += NUM_YEARS) { storage[i][j][k] = year_ptr; } } } memset(storage[0][0][0],0,num_rows*num_columns*NUM_YEARS*NUM_DAYS*sizeof(float)); row_ptr = (float****)malloc(sizeof(float ***)*num_rows); column_ptr = (float***)malloc(sizeof(float **)*num_rows * num_columns); day_ptr = (float**)malloc(sizeof(float *)*num_rows * num_columns*NUM_DAYS); year_ptr = (float*)malloc(sizeof(float)*num_rows*num_columns*NUM_YEARS*NUM_DAYS); float ****count = row_ptr; for (i = 0; i < num_rows; i++, column_ptr += num_columns) { count[i] = column_ptr; for (j = 0; j < num_columns; j++, day_ptr += NUM_DAYS) { count[i][j] = day_ptr; for (k = 0; k < NUM_DAYS; k++, year_ptr += NUM_YEARS) { count[i][j][k] = year_ptr; } } } // memset(count[0][0][0],0,num_rows*num_columns*NUM_YEARS*NUM_DAYS*sizeof(float)); for (i = 0; i < num_rows; i++) { for (j = 0; j < num_columns; j++) { for (k = 0; k < NUM_DAYS; k++) { for (m = 0; m < NUM_YEARS; m++) { count[i][j][k][m] = 1; } } } } printf("Done\n"); // get list of files to be opened char warp_fname[] = "/home/lindell/workspace/soil_moisture/sm_gen_warp_images/warp.list"; FILE* file_id = fopen(warp_fname,"r"); if (file_id == NULL) { fprintf(stderr,"*** could not open list file %s\n",warp_fname); exit(-1); } // count lines in file char ch; size_t list_len = 0; while(!feof(file_id)) { ch = fgetc(file_id); if (ch == '\n') ++list_len; } // reset file pointer and put filenames into array buffer rewind(file_id); int fname_i = 0; char fname[150]; char **warp_list; warp_list = malloc(list_len * sizeof(char*)); for (i = 0; i < list_len; i++) warp_list[i] = malloc((150) * sizeof(char)); while (fgets(fname,sizeof(fname),file_id)!=NULL) { remove_newline(fname); strcpy(warp_list[fname_i],fname); ++fname_i; } printf("Preparing for processing...\n"); // sort through pixels/images // split up row processing based on number of threads/files ind_per_thread = (list_len-1) / NUM_THREADS; if ((ind_per_thread % 2) == 0) { ind_per_thread--; } start_index = 0; stop_index = 0; for (i = 0; i < NUM_THREADS; i++) { if (i == NUM_THREADS - 1) { stop_index = list_len-1; } else { stop_index = start_index + ind_per_thread; } t_args[i].storage = storage; t_args[i].count = count; t_args[i].start_i = start_index; t_args[i].stop_i = stop_index; t_args[i].num_rows = num_rows; t_args[i].num_columns = num_columns; t_args[i].region = region; t_args[i].fopen_lock = &fopen_lock; t_args[i].warp_list = warp_list; t_args[i].head = &head; start_index = stop_index + 1; } // submit threads for (i = 0; i < NUM_THREADS; i++) { pthread_create(&thread_id[i], NULL, mthreadLoadImg, &t_args[i]); } // join threads for (i = 0; i < NUM_THREADS; i++) { pthread_join(thread_id[i], NULL); } // save storage array to netcdf file printf("Done processing, preparing to save files\n"); // malloc a temp array; float **tmp_arr = malloc(sizeof(float**)*num_rows); tmp_arr[0] = malloc(sizeof(float)*num_rows*num_columns); for (i = 0; i < num_rows; i++) { tmp_arr[i] = tmp_arr[0] + i*num_columns; } memset(tmp_arr[0],0,num_rows*num_columns*sizeof(float)); int year_i; int day_i; for (year_i = 0; year_i < NUM_YEARS; year_i++) { for (day_i = 0; day_i < NUM_DAYS; day_i++) { printf("Saving data for %03d %d...\n",day_i*2+1,year_i+2007); // copy data from storage into temp array for (i = 0; i < num_rows; i++) { for (j = 0; j < num_columns; j++) { tmp_arr[i][j] = storage[i][j][day_i][year_i]; if (count[i][j][day_i][year_i] == 1) { tmp_arr[i][j] = -1; // set nodata flag } } } sprintf(FILE_NAME,"/auto/temp/lindell/soilmoisture/warp/%s_%04d_%03d.nc",region,year_i+2007,day_i*2+1); if ((retval = nc_create(FILE_NAME, NC_NETCDF4, &ncid))) { ERR(retval); continue; } /* Define the dimensions. */ if ((retval = nc_def_dim(ncid, "row", num_rows, &row_dimid))) { ERR(retval); continue; } if ((retval = nc_def_dim(ncid, "column", num_columns, &col_dimid))) { ERR(retval); continue; } /* Define the netCDF variables. The dimids array is used to pass the dimids of the dimensions of the variables.*/ dimids[0] = row_dimid; dimids[1] = col_dimid; /* define the variable */ if ((retval = nc_def_var(ncid, "sm", NC_FLOAT, NDIMS, dimids, &varid))) ERR(retval); /* End define mode. */ if ((retval = nc_enddef(ncid))) ERR(retval); /* Write the data. */ if ((retval = nc_put_var_float(ncid, varid, &tmp_arr[0][0]))) ERR(retval); /* Close the file. */ if ((retval = nc_close(ncid))) ERR(retval); // clear the tmp array memset(tmp_arr[0],0,num_rows*num_columns*sizeof(float)); } } free(tmp_arr[0]); free(tmp_arr); // Free memory for 3D image timeseries array printf("Finishing up..."); free(storage[0][0][0]); free(storage[0][0]); free(storage[0]); free(storage); free(count[0][0][0]); free(count[0][0]); free(count[0]); free(count); for (i = 0; i < list_len; i++) free((void*)warp_list[i]); free((void*)warp_list); printf("done\n"); exit (0); }
graph_t * load_graph (FILE * fdnodes, FILE * fdarcs){ unsigned int i; graph_t *graph; /* punterà al grafo da creare */ char *app, *p, *segna_posto, *line, *flag; /* vari puntatori ausiliari */ edge_t *aux, *helper; /* - dim conterrà l'esatta dimensione della stringa rappresentante il nodo sorgente, - i_sorg e i_dest conterranno gli indici dei nodi sorg/dest dell'arco letto */ int conta = ZERO, dim, i_sorg, i_dest; if( !fdnodes || !fdarcs ){ /* file non esistenti o errore nella precedente apertura?? */ errno = EINVAL; return NULL; } /* ---FASE 1--- : creazione nodi sorgente */ MALLOC_IF(app, sizeof(char), PDIM2) while ( fgets(app, PDIM2 - UNO, fdnodes) ) /* per la correttezza della struttura da allocare, mi serve sapere quanti nodi leggerò */ conta++; free(app); if(conta <= ZERO){ errno = EINVAL; return NULL; } MALLOC_IF(graph, sizeof(graph_t), UNO) if( !(MALLOC(graph->node, sizeof(node_t), conta)) ){ /* allocazione array dei 'conta' nodi */ free(graph); return NULL; } graph->size = conta; rewind(fdnodes); /* inserimento nodi */ for(i = ZERO; i < conta ;i++){ /* char * PDIM2 = (LLABEL+2) considerando anche il '\n' letto e il '\0' inserito dalla fgets */ if( !(MALLOC(app, sizeof(char), PDIM2) ) ){ free_graph(&graph); return NULL; } fgets( app, PDIM2, fdnodes); /* copia in app un intera riga del file (compreso il carattere '\n' : risulterà d'intralcio per la successivi confronti (es. chiamata di is_node); allora lo elimino... */ dim = strlen(app); app[dim - UNO] = TCHAR; /* e al suo posto inserisco '\0' per terminare la stringa */ if( !check_node(&app,UNO) || !( MALLOC( ((graph->node)+i)->label, sizeof(char), dim)) ){ free(app); free_graph(&graph); return NULL; } strncpy( ((graph->node)+i)->label, app, dim); /* copio la stringa fino all'ex '\n' compreso (ora '\0') */ free(app); ((graph->node)+i)->adj = NULL; } /* ---FASE 2--- : creazione archi */ MALLOC_IF(app, sizeof(char), PDIM1) while( (fgets( app, PDIM1 - UNO, fdarcs)) ){ /* start loop per la lettura delle stringhe-arco */ /* 1° PARTE: nodo sorgente */ segna_posto = strchr(app,':'); /* check di correttezza della 1° parte della stringa letta */ if( !segna_posto || !check_edge(app, segna_posto, TRUE) ){ STD_OUT1 } MALLOC_IF(p, sizeof(char), LLABEL+UNO) /* per contenere il nodo sorgente: stavolta basta +1, dato che non viene letto '\n' */ flag = app + (parzial_cpy(p, app, segna_posto)); /* copio la parte relativa al nodo sorgente e mi sistemo dopo i primi ':' */ if( (i_sorg = is_node(graph,p)) < ZERO){ free(p); STD_OUT1 } free(p); /* 2° PARTE: nodo destinazione */ /* mi sistemo sui secondi ':' e lancio un check sulla correttezza della 2° sottostringa (relativa al nodo destinazione) */ segna_posto = strchr(flag,':'); if( !segna_posto || !check_edge(flag, segna_posto, TRUE) ) { STD_OUT1 } MALLOC_IF(p, sizeof(char), LLABEL+UNO) flag = flag + parzial_cpy(p,flag,segna_posto); /* copio la seconda sottostringa e mi sistemo subito dopo i secondi ':' */ /* 3° parte: distanze in km + creazione elemento lista di adiacenza del nodo sorgente; non proseguo se il nodo destinazione non è valido, se esiste già un arco uguale a quello che vogliamo aggiungere oppure se la 3° sottostringa (relativa alla distanza in km) è malformata*/ line = remove_newline(flag); if( ((i_dest = is_node(graph,p)) < ZERO) || ((is_edge(graph,i_sorg,i_dest)) ) || !check_edge(line, segna_posto, FALSE) ){ free(p); free(line); STD_OUT1 }
int main(int argc, char **argv) { program_name = basename(argv[0]); snprintf(doc,DOC_BUFFER_LEN,"%s -- a simple client for COMP-535",program_name); struct arguments arguments; /* Default values. */ arguments.port = -1; arguments.host = NULL; arguments.adaptive = 0; arguments.verbose = 0; arguments.silent = 0; arguments.batch = 0; arguments.devnull = 0; arguments.infile = NULL; argp_parse (&argp, argc, argv, 0, 0, &arguments); verbose_f = 0; if (arguments.verbose) verbose_f = 1; if (arguments.silent) { freopen("/dev/null", "w", stderr); freopen("/dev/null", "w", stdout); } batch_f = arguments.batch; adaptive_f = arguments.adaptive; if (arguments.infile) { if(freopen(arguments.infile, "r", stdin) == NULL){ exit(1); } } sockfd = -1; if (adaptive_f) adaptivefd = -1; signal(SIGINT, interrupt); char foldertmp[] = "clientimgXXXXXX"; char s[INET6_ADDRSTRLEN], *t, *line, linebuf[LINE_SIZE]; char *filename, *filebuf; int cid, l; /* Return values, temp values */ FILE *file; size_t filesize, read, remain, total, chunk; sockfd = connect_to_host(arguments.host, arguments.port, s, sizeof s); if (sockfd == -1) { fprintf(stderr, "failed to connect to server.\n"); global_exit(1); } fprintf(stdout, "Connected to %s\n", s); buffer = ALLOC(readbuffer); buffer->used = 0; // HELLO YES THIS IS SERVER line = recvline(); t = strtok(line,DELIM); if (strcmp(t, "HELLO") != 0){ fprintf(stderr,"Unexpected message from server: %s\nExiting.\n", line); global_exit(0); } t = strtok(NULL,DELIM); cid = (int)strtol(t,NULL,0); if (errno == ERANGE) { /* Not a number? or number too big? */ fprintf(stderr, "Invalid client ID from server. Exiting"); global_exit(1); } fprintf(stdout, "Got client ID: %d\n", cid); if (adaptive_f) { if ((t = strtok(NULL,DELIM)) == NULL){ fprintf(stderr, "Server is not in adaptive mode. Exiting\n"); global_exit(1); } errno = 0; l = (int)strtol(t,NULL,0); if (errno == ERANGE) { /* Not a number? or number too big? */ fprintf(stderr, "Invalid port number from server. Exiting"); global_exit(1); } adaptivefd = connect_to_host(arguments.host, l, NULL, 0); if (adaptivefd == -1) { fprintf(stderr, "failed to connect to adaptive server.\n"); global_exit(2); } snprintf(linebuf, LINE_SIZE, "%d\n", cid); if (send(adaptivefd, linebuf, strlen(linebuf), 0) == -1){ perror("send"); global_exit(1); } } efree(line); if (!arguments.devnull){ mkdtemp(foldertmp); fprintf(stdout, "Storing downloaded images in directory %s.\n", foldertmp); } for (;;) { #ifdef HAS_GNUREADLINE if(snreadline(linebuf, LINE_SIZE, "GET> ") == NULL){ #else if (!batch_f) fprintf(stderr, "GET> "); if(fgets(linebuf, LINE_SIZE, stdin) == NULL){ #endif printf("exit\n"); global_exit(0); } #ifndef HAS_GNUREADLINE trim_in_place(linebuf); #endif if (strlen(linebuf) == 0) continue; /* Hacky hack to transmit panning speed, any 2 or less digit number is considered a pan speed */ if (adaptive_f && strlen(linebuf) < 3 && is_number(linebuf)) { add_newline(linebuf, LINE_SIZE); if (send(adaptivefd, linebuf, strlen(linebuf), 0) == -1){ perror("send"); global_exit(1); } continue; } if (add_newline(linebuf, LINE_SIZE)) { fprintf(stderr, "Command too long.\n"); continue; } if (send(sockfd, linebuf, strlen(linebuf), 0) == -1){ perror("send"); global_exit(1); } remove_newline(linebuf); line = recvline(); t = strtok(line,DELIM); if (strcmp(t, "ERROR") == 0){ t = strtok(NULL,DELIM); fprintf(stderr, "Server> Error: %s\n", t); } else if (strcmp(t, "FILE") == 0) { t = strtok(NULL,DELIM); errno = 0; size_t filesize = (size_t)strtol(t,NULL,0); if (errno == ERANGE) { fprintf(stderr,"Fatal Error: Could not parse file size.\n", t); global_exit(0); } if (!arguments.devnull) { l = snprintf(NULL, 0, "%s/%s", foldertmp, linebuf); filename = (char *)emalloc(l+1); snprintf(filename, l+1, "%s/%s", foldertmp, linebuf); } else { filename = (char *)emalloc(10); snprintf(filename, 10, "/dev/null"); } file = fopen(filename,"wb"); efree(filename); chunk = (filesize > MAX_FILE_BUFFER) ? MAX_FILE_BUFFER : filesize; filebuf = (char *)emalloc(chunk); remain = filesize; total = 0; if (buffer->used > 0){ fwrite(buffer->data, 1, buffer->used, file); total += buffer->used; remain -= buffer->used; buffer->used = 0; } fprintf(stderr,"'%s' [%ld/%ld] (%ld%%)", linebuf, (long)total, (long)filesize, (long)(100*total)/filesize); while (remain > 0) { read = recv(sockfd, filebuf, chunk, 0); if (read == -1) { perror("recv"); global_exit(3); } else if (read == 0) { fprintf(stderr,"Server dropped connection.\n"); global_exit(4); } total += read; remain -= read; fprintf(stderr,"%c[2K\r", 27); fprintf(stderr,"'%s' [%ld/%ld] (%ld%%)", linebuf, (long)total, (long)filesize, (long)(100*total)/filesize); fwrite(filebuf, 1, read, file); } fprintf(stderr,"%c[2K\r", 27); printf("'%s' saved. [%ld/%ld]\n", linebuf, (long)total, (long)filesize); fclose(file); efree(filebuf); } else { verbose("Ignoring unexpected message from server: %s\n", t); } efree(line); } }
int main(int argc, char ** argv){ cgi datCGI; char * teach=NULL; char * acceptTOS=NULL; person reg_person; bool pw_short=false; init_person(®_person); init_CGI(&datCGI); get_CGI_data(&datCGI); if(datCGI.request_method == GET){ print_exit_failure("Use POST!"); } //Für die Namen: siehe HTML-Dokument mit entsprechenden <input>-Elementen extract_POST_data(&datCGI, "name_vor", ®_person.first_name); remove_newline(reg_person.first_name); clean_string(reg_person.first_name); extract_POST_data(&datCGI, "name", ®_person.name); remove_newline(reg_person.name); clean_string(reg_person.name); extract_POST_data(&datCGI, "email", ®_person.email); remove_newline(reg_person.email); clean_string(reg_person.email); extract_POST_data(&datCGI, "pass", ®_person.password); remove_newline(reg_person.password); extract_POST_data(&datCGI, "acronym", ®_person.acronym); remove_newline(reg_person.acronym); clean_string(reg_person.acronym); extract_POST_data(&datCGI, "teach", &teach); remove_newline(teach); extract_POST_data(&datCGI, "acceptTOS", &acceptTOS); remove_newline(acceptTOS); //TODO: fehlerhaften Aufruf abfangen if(strcmp(teach, "true") == 0){ reg_person.isTeacher=true; if(strlen(reg_person.acronym) != 3){ print_html_error("Das Kürzel muss genau 3 Zeichen lang sein", "/registrierung.html"); exit(EXIT_FAILURE); } }else{ reg_person.isTeacher=false; } //Die E-Mail-Adresse muss genau EIN '@' beinhalten if((strchr(reg_person.email, '@') == strrchr(reg_person.email, '@')) && strchr(reg_person.email, '@')) { #ifdef DEBUG fprintf(stderr, "es scheint alles zu passen (EMAIL)\n"); #endif // DEBUG if(strlen(reg_person.password)<8){ pw_short=true; } insert_user(®_person); } //fprintf(stderr, "\nnow comes da htmlz\n"); httpCacheControl("no-store, no-cache, must-revalidate, max-age=0"); httpHeader(HTML); //printf("%s\n", datCGI.POST_data); print_html_head("Passwort erneut eingeben", "Verifikation"); puts("<body>\n\ <div id='login-form'>\n"); printf("<p><span>Herzlich willkommen <span style='font-weight: bold;'>%s %s.</span><br>Bitte %s zum Anmelden %s Passwort ein</p>\n", reg_person.first_name, reg_person.name, reg_person.isTeacher ? "geben Sie" : "gib", reg_person.isTeacher ? "Ihr" : "dein" ); printf("<form method='post' action='/cgi-bin/login.cgi' style='border-radius: 1em; padding: 1em;' autocomplete='off'>\n\ <input type='hidden' name='email' value='%s' />\n\ <input class='textIn' placeholder='Passwort' type='password' id='pass' name='pass' required>\n\ <button class='submitButton' type='submit'>Anmelden*</button>\n\ </form>\n",reg_person.email); puts("<small>* Cookies müssen aktiviert sein!</small>\n"); if(pw_short){ puts("<br><small style='color: yellow; background-color: red;'>Sie sollten wirklich ein längeres Passwort verwenden!!</small>\n"); } puts("</div>\n</body>\n</html>\n"); /*puts("Erhaltene Daten:\n"); printf("CONTENT_LENGTH: %d\n", datCGI.content_length); printf("Name: %s\nPassword: %s\n", reg_person.name, reg_person.password); printf("Kuerzel: %s\nTeach: %s\n", reg_person.acronym, teach); printf("accepted TOS: %s\n\n", acceptTOS); printf("Post Data: %s\n", datCGI.POST_data);*/ exit(0); }
void shell() { current_database = -1; char entrada[1000], nomeBD[TAM_NOME_BANCO]; int resultado = 0, codDB = -1; nomeBD[0]='\0'; char *current_db_name = strdup(">");//inicializa com nenhum banco conectado char *start; start = strdup("dbms-start");//este comando posteriormente como start do banco, no momento ele é automatico printf("\nWelcome to the DBMS Interface.\nType 'help' '\\h' for help.\n\n"); /** * **************************** * * Comandos do shell * * **************************** */ using_history ();//função para usar o histórico read_history (".history_file"); while(1) { int nTokens; strcpy(entrada, readline(current_db_name)); /** * Adiciona ao histórico */ if (entrada[0]) { char *expansion; int result; result = history_expand (entrada, &expansion); if (result) fprintf (stderr, "%s", expansion); if (result < 0 || result == 2) { free (expansion); continue; } add_history (expansion); strncpy (entrada, expansion, sizeof (entrada) - 1); free (expansion); write_history (".history_file");//adiciona no histórico } char **tokens = tokenize( trim_white_space(remove_newline(entrada)),' ',&nTokens); /** * Opção para criar tabela e banco de dados */ if (strcmp(strtolower(tokens[0]),"create")==0) { if(strcmp(strtolower(tokens[1]),"table")==0) { if (current_database == -1) { printf("Not connected to any database.\n"); continue; } createTable(entrada,current_database); } else if(strcmp(strtolower(tokens[1]),"database")==0) { if (nTokens >= 5) { printf("Invalid command. Type help to show de interface usage.\n"); continue; } if (strlen(tokens[2]) > TAM_NOME_BANCO ) { printf("Database name too big.\n"); continue; } resultado = checkCreateDB( remove_semicolon(tokens[2]) );//verifica a existência do nome e grava-o no arquivo if(resultado==-1) { printf("Error creating database file.\n"); } if(resultado==-3) { printf("Database exists.\n"); } else { printf("Database created successfully.\n"); } } else { printf("Invalid command. Type help to show de interface usage.\n"); continue; } } /** * Conecta ao banco de dados passado como parâmetro */ else if(strcmp(strtolower(tokens[0]),"\\c") == 0){ if (nTokens != 2) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); continue; } char *name_db = remove_semicolon(tokens[1]); codDB = busca(name_db,1); //função chamada para conecção no banco, retorna o codigo do banco ao conectar if (codDB >= 0) { strcpy(nomeBD, name_db); //passa o nome do bd, para a variavel mostrar ao usuario qual o banco conectado free(current_db_name); current_db_name = (char*) malloc (sizeof(char)*(strlen(name_db)+3)); if (current_db_name == NULL) { printf("Out of memory.\nAborting...\n"); } strcpy(current_db_name,name_db); current_database = codDB; strcat(current_db_name,"=#"); current_db_name[strlen(current_db_name)] = '\0'; } else { printf("No such database '%s'.\n", name_db); continue; } } /** * Insere tuplas em uma tabela */ else if(strcmp(strtolower(tokens[0]),"insert")==0) { if (current_database == -1) { printf("Not connected to any database.\n"); continue; } insert(entrada,current_database); } /** * Imprime as tabelas do banco de dados atual * ou o esquema de uma tabela */ else if(strcmp(strtolower(tokens[0]),"\\d")==0) { if (current_database == -1) { printf("Not connected to any database.\n"); continue; } if (nTokens >= 3) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); continue; } else if (nTokens == 1) { //imprime tabelas do banco de dados listaTabelas(current_database); } else { //imprime o esquema de uma tabela char *t = table_name_real(remove_semicolon(tokens[1]),current_database); if(!verificaNomeTabela(t)){ printf("Invalid table name.\n"); free(t); continue; } struct fs_objects objeto = leObjeto(t);//para verificar se a tabela esta no banco show_schema(objeto,tokens[1]); free(t); } } /** * Comando temporário para imprimir tabela */ else if (strcmp(strtolower(tokens[0]),"select")==0) { if (current_database == -1) { printf("Not connected to any database.\n"); continue; } selectTable(entrada,current_database); } /** * Imprime os registros da tabela passada */ else if (strcmp(strtolower(tokens[0]),"show")==0) { if (nTokens != 2) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); continue; } if (current_database == -1) { printf("Not connected to any database.\n"); continue; } if (verificaNomeTabela(table_name_real(remove_semicolon(tokens[1]),current_database) ) == 0 ) { printf("Table %s doesn't exist.\n",remove_semicolon(tokens[1])); continue; } char *t = table_name_real(remove_semicolon(tokens[1]),current_database); char *file = table_name_real(remove_semicolon(tokens[1]),current_database); strcat(file,".dat"); if (existeArquivo(file) == 0) { printf("Table is empty.\n" ); continue; } imprime(t); free(file); free(t); } /** * Lista os bancos existentes */ else if(strcmp(strtolower(tokens[0]),"\\l")==0) { if (nTokens != 1) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); continue; } //LISTA os bancos existentes listaBancos(); } /** * Opção para deletar o banco de dados e tabelas */ else if(strcmp(strtolower(tokens[0]),"drop")==0) { if (nTokens != 3) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); continue; } else if(strcmp(strtolower(tokens[1]),"table") == 0){ if (current_database == -1) { printf("Not connected to any database.\n"); continue; } if (verificaNomeTabela(table_name_real(remove_semicolon(tokens[2]),current_database) ) == 0 ) { printf("Table %s doesn't exist.\n",remove_semicolon(tokens[2])); continue; } char *t = table_name_real(remove_semicolon(tokens[2]),current_database); char *exist = table_name_real(remove_semicolon(tokens[2]),current_database); int ok = excluirTabela(t); if (ok == SUCCESS) { printf("Table deleted successfully.\n"); } free(exist); free(t); } else if(strcmp(strtolower(tokens[1]),"database") == 0){ char *exist = table_name_real(remove_semicolon(tokens[2]),current_database); strcat(exist,".dat"); if (existeArquivo(exist) != 0) { printf("The database is not empty for drop, there are existing tables.\n" ); continue; } exist = remove_semicolon(tokens[2]); codDB = busca(exist,1); if(codDB == current_database) { printf("Cannot drop the currently open database.\n"); continue; } int drop = dropDatabase(remove_semicolon(tokens[2])); if(drop == 1)printf("Database deleted successfully.\n"); free(exist); } } /** * Ajuda ao usuário com exemplos da sintaxe dos comandos */ else if (strcmp(strtolower(tokens[0]),"help")==0 || strcmp(strtolower(tokens[0]),"\\h")==0) { if (nTokens != 1) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); } help(); } /** * Imprime mensagem de copyright */ else if(strcmp(strtolower(remove_semicolon(tokens[0])),"\\copyright")==0) { printf("\nDatabase Management System\n"); printf("\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose, without fee, and without a written agreement\nis hereby granted, provided that the above copyright notice and this\nparagraph and the following two paragraphs appear in all copies.\n"); printf("\nTHIS SOFTWARE IS BEING DEVELOPED BY STUDENTS OF DATABASE II CLASS AT UNIVERSIDADE FEDERAL DA FRONTEIRA SUL.\n\n"); } /** * Comando de saída */ else if(strcmp(strtolower(remove_semicolon(tokens[0])),"exit")==0) { break; } else if(strcmp(strtolower(remove_semicolon(tokens[0])),"quit")==0) { break; } else if(strcmp(strtolower(remove_semicolon(tokens[0])),"bye")==0) { break; } else if(strcmp(strtolower(remove_semicolon(tokens[0])),"\\q")==0) { break; } else { printf("Invalid command. Type help to show the interface usage.\n"); continue; } } free(start); free(current_db_name); }
int main(int argc, char **argv){ // Declaration // File to search in char *input_file = NULL; // Flag to check if input file was given int input_given =0; // Loop through arguments to get passed in options // Start on argv[1] because [0] is program name for(int i=1;i<=argc-1;i++){ // Parse arguments if(argv[i][0]=='-' && strlen(argv[i])==2){ switch(argv[i][1]){ case 'i' : // if "-i" change input_file to filename passed in input_file = (char*)malloc(strlen(argv[i+1])); strcpy(input_file,argv[i+1]); input_given = 1; break; default: printf("--Error parsing arguments.--\n"); exit(EXIT_FAILURE); break; } } } FILE *ifp; //Open input file //If file fails to open, output message and exit if(!input_given){ ifp = stdin; }else if((ifp = fopen(input_file, "r")) == NULL){ printf("Can't open input file: %s\n",input_file); exit(EXIT_FAILURE); }else{ printf("Opened file: %s to read from\n",input_file); } // To simplify, max length for the description is 200 chars char description[200]; char line[200]; // Get the first line and put it in description // If input is taken from stdin, print a message to the user if(!input_given){ printf("Enter the description for your route\n"); } fgets(description, 200, ifp); remove_newline(description); double total = 0; // Temp char* for the tokens when using strtok char *token; // Flag for user input int cont_input =1; // Initialise latitudes and longitudes to values that aren't possible values // Latitude is never > 90 or < -90 and Longitude is never > 180 or < -180 double lat1; double lon1; double lat2 = 111; double lon2 = 222; int counter = 0; if(!input_given){ printf("Enter coordinates in the following format:\n"); printf("\t[latitude],[longitude]\n"); printf("After entering all the coordinated type --quit--\n"); } while(cont_input == 1 && (total == 0 || cont_input == 1) && (fgets(line, 512, ifp) != NULL)){ if(!strcmp(line,"--quit--\n")){ // Change condition to break out of the loop cont_input = 0; }else{ if(sscanf(line,"%lf,%lf\n",&lat1,&lon1) == 2){ #ifdef DEBUG printf("Just got values\n"); #endif // Check that all values are usable if(validate_lat(&lat1) && validate_lat(&lat2) && validate_lon(&lon1) && validate_lon(&lon2)){ #ifdef DEBUG printf("RUNNING WITH VALUES:\n"); printf("\t--LAT1:%f\n\t--LON1:%f\n\t--LAT2:%f\n\t--LON2:%f\n", lat1,lon1,lat2,lon2); #endif total += dist(lat1,lon1,lat2,lon2); #ifdef DEBUG printf("NEW TOTAL: %f\n",total); #endif }else{ error(&input_given,&counter); } // Swap values lat2 = lat1; lon2 = lon1; // Increase number of inputs taken counter++; #ifdef DEBUG printf("Number of inputs so far: %d\n",counter); #endif }else{ error(&input_given,&counter); } } } // Print number of coordinates read if there was more than one given if(counter <= 1){ printf("I need more coordinates\n"); } if(total <= 0){ printf("You gave me several places, but I need different ones to calculate a distance\n"); } if(counter > 1 && total > 0){ printf("Coordinates read: %d\n", counter); /* Americans don't know kilometers */ printf("%s: %.1f km (%.1f mi.)\n",description, total, total / 1.609344); }else{ exit(EXIT_FAILURE); } //Close the files if still open. if(ifp && input_given){ fclose(ifp); } // Free memory allocated for the file name if(input_file != NULL){ free(input_file); } return 0; }
command_stream_t make_command_stream(int (*get_next_byte) (void *), void *get_next_byte_argument) { /* FIXME: Replace this with your implementation. You may need to add auxiliary functions and otherwise modify the source code. You can also use external functions defined in the GNU C Library. */ token_t t = checked_malloc(sizeof(struct token)); token_t head = t; t->prev = NULL; t->str = checked_malloc(sizeof(char)); t->str[0] = '\0'; t->type = EMPTY; char* inputStream = makeInputStream(get_next_byte, get_next_byte_argument); while(1) { token_t temp = get_next_token(inputStream, t); //printf("%s %d\n", temp->prev->str, temp->prev->type); //printf("%s %d\n", temp->str, temp->type); if(temp->str[0] == EOF) { t = temp; break; } t = temp; } t->next = NULL; t = remove_whitespace(head); // while (t != NULL) // { // //printf("%s %d\n", t->str, t->type); // //if (t -> next != NULL) { // //printf("%s %d\n", t->next->str, t->next->type); // //} // t = t->next; // } convert_to_simple(head); remove_newline(head); // t = head; // while (t != NULL) // { // printf("%s %d\n", t->str, t->type); // //if (t -> next != NULL) { // //printf("%s %d\n", t->next->str, t->next->type); // //} // t = t->next; // } //remove_newline(head); // t = head; // while (t != NULL) // { // //printf("%s %d\n", t->str, t->type); // //if (t -> next != NULL) { // //printf("%s %d\n", t->next->str, t->next->type); // //} // t = t->next; // } command_stream_t stream = make_command(head); command_stream_t c = checked_malloc(sizeof(struct command_stream)); c->head = NULL; c->tail = NULL; while(stream->head != NULL) { struct command_node *n = stream->head->next; stream->head->next = c->head; c->head = stream->head; stream->head = n; } // while(c->head != NULL) // { // printf("new command\n"); // print_command(c->head->command); // c->head = c->head->next; // } // t = head; // while(t != NULL) // { // token_command_t c = get_next_command(t); // //printf("%s\n", t->str); // if(c != NULL) // { // if(c->type == SIMPLE) // { // int i = 0; // while(c->command->u.word[i] != '\0') // { // //printf("%d:%s\n", i, c->command->u.word[i]); // i=i+1; // } // } // else // { // //printf("%s %d\n", t->str, c->type); // } // //printf("\n"); // } // t = t->next; // } return c; }
/** Benutzer anmelden (Passwort Überprüfen) */ int main(int argc, char ** argv) { cgi datCGI; init_CGI(&datCGI); person login_person; init_person(&login_person); //fprintf(stderr, "Hallo vor Post\n"); get_CGI_data(&datCGI); if(datCGI.request_method != POST) { print_exit_failure("Use POST!"); } //fprintf(stderr, "POST_DATA: %s", datCGI.POST_data); //Aus POST_data den String zwischen <AttributName>= und '&' ausschneiden extract_POST_data(&datCGI, "email", &login_person.email); remove_newline(login_person.email); extract_POST_data(&datCGI, "pass", &login_person.password); remove_newline(login_person.password); if(login_person.email == NULL) { httpSetCookie("EMAIL", "NULL"); httpSetCookie("SID", "0"); httpCacheControl("no-cache"); char * redirectString=NULL; asprintf(&redirectString, "https://%s/incorrect_password.html", datCGI.http_host); httpRedirect(redirectString); } //fprintf(stderr, "POST_DATA: %s", datCGI.POST_data); //TODO: Verhindern, dass sich ein anderer Nutzer vom selben Rechner aus einloggt wenn der erste noch nicht abgemeldet ist //(zweimaliges Anmelden verhindern) //Das ist sehr unwahrscheinlich /* if(datCGI.http_cookies != NULL){ person already_logged_in_person; init_person(&already_logged_in_person); char * cook_sid=NULL; if(extract_COOKIE_data(&datCGI, "EMAIL", &already_logged_in_person.email) == 0 && extract_COOKIE_data(&datCGI, "SID", &cook_sid) == 0){ //print_exit_failure("Hier ist schon jemand eingeloggt"); already_logged_in_person.sid=atoi(cook_sid); if(get_person_by_sid(&already_logged_in_person)){ print_exit_failure("Hier ist schon jemand eingeloggt"); } } }*/ UserState user_state=verify_user(&login_person); //Zwei cookies setzen if(user_state == PW_CORRECT || user_state == PW_CORRECT_ALREADY_LOGGED_IN) { httpSetCookie("EMAIL", login_person.email); char * sid_string; asprintf(&sid_string, "%d", login_person.sid); httpSetCookie("SID", sid_string); httpCacheControl("no-store, no-cache, must-revalidate, max-age=0"); char * redirectString=NULL; asprintf(&redirectString, "https://%s/cgi-bin/all_messages.cgi", datCGI.http_host); httpRedirect(redirectString); } if(user_state == PW_INCORRECT) { httpSetCookie("EMAIL", "NULL"); httpSetCookie("SID", "0"); httpCacheControl("no-store, no-cache, must-revalidate, max-age=0"); char * redirectString=NULL; asprintf(&redirectString, "https://%s/incorrect_password.html", datCGI.http_host); httpRedirect(redirectString); } /* httpHeader(HTML); printf("<!DOCTYPE html><head>\ <title>InfoWall -- Anmeldung</title>\ <meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" />\ <meta name=\"viewport\" content=\"width=device-width\">\ </head>\ <body>"); printf("%s\n", datCGI.POST_data); puts("<h1>Erhaltene Daten:</h1>\n"); printf("<br>CONTENT_LENGTH: %d -- REQUEST_METHOD: %s\n", datCGI.content_length, datCGI.request_method); printf("<br>Name: %s\nPassword: %s\n", login_person.email, login_person.password); printf("<br>Post Data: %s\n", datCGI.POST_data); puts("<br>\n\n\n\n"); if(login_person.auth && user_state==0){ puts("<h2>Personendaten:</h2>\n"); printf("<br>User ID: %d\n", login_person.id); printf("<br>Vorname: %s\n", login_person.first_name); printf("<br>Nachname: %s\n", login_person.name); printf("<br>Email: %s\n", login_person.email); printf("<br>Passwort: %s (richtig)\n", login_person.password); printf("<br>Faecher: %s\n", login_person.courses); if(login_person.isTeacher)printf("<br>Kuerzel: %s\n", login_person.acronym); printf("<br>SID: %d\n", login_person.sid); puts("<a href=\"/cgi-bin/logout.cgi\" style=\"color: green;\">LOGOUT</a>\ <br><a href=\"/cgi-bin/all_messages.cgi\">Alle Nachrichten</a>"); puts("<iframe src=\"/cgi-bin/all_messages.cgi\" style=\"width: 100%; height: 500px;\""); }else{ puts("<br>YOU FAIL!!\n"); if(user_state == 1){ puts("Bereits angemeldet!"); printf("<a href=\"/cgi-bin/logout.cgi\">LOGOUT</a>\ <br><a href=\"/cgi-bin/all_messages.cgi\">Alle Nachrichten</a>"); } } printf("</body>\ </html>");*/ exit(0); }