Пример #1
0
static int do_connected(void)
{
  while (!exitasap) {
    if (read_lines())
      break;
  }
  
  /* Keep capturing lines as long as there are lines ready to read. */
  while (!exitasap) {
    if (seq_next - seq_send >= startlines)
      return STATE_SENDING;
    switch (iopoll(io, 1, readwait)) {
    case -1:
      return STATE_EXITING;
    case 1:
      if (stdin_error)
	return exitoneof ? STATE_EXITING : STATE_SENDING;
      if (read_lines() > 0 || stdin_eof)
	return STATE_SENDING;
      continue;
    case 0:
      return STATE_SENDING;
    }
  }
  return STATE_EXITING;
}
Пример #2
0
// printer processes the arguments and calls read_lines
// with the appropriate arguments. This line is mostly
// copied from Prof. Mackey's 'catbyline.c'. 
void printer(int argc, char **argv, int *flags) {
   // position of the first null in the arguments
   int null_pos = find_null (argv);
   // string to search files for
   char *search = argv[null_pos-argc];
   // sends to read_lines with standard input if no files provided
   if (argc==1) {
      read_lines (stdin, STDIN_NAME, search, argc-1,flags);
   } else {
      // loop over filenames
      for (int argi=null_pos-argc+1; argi<null_pos; ++argi) {
         char *filename = argv[argi];
         if (strcmp (filename, STDIN_NAME) == 0) {
            read_lines (stdin, STDIN_NAME, search, argc-1,flags);
         }else {
            // loop for valid filenames
            FILE *input = fopen (filename, "r");
            if (input != NULL) {
               read_lines (input, filename, search, argc-1,flags);
               fclose (input);
            }else {
               exit_status = EXIT_FAILURE;
               fflush (NULL);
               fprintf (stderr, "%s: %s: %s\n", argv[0],
                        filename, strerror (errno));
               fflush (NULL);
            }
         }
      }
   } 
}
Пример #3
0
int main(int argc, char **argv)
{
    ptable_s table;
    supermach_s *machine;
    printf("reading: %s\n",argv[1]);

    machine = build_smachine (_COMPINITID_, MACH_ARGS);

    if (argc < 2)
        read_lines(machine, "samples/workingtest");
    else
        read_lines(machine, argv[1]);
    populate_reserved (machine, "keywords");
    run_machine (machine);
    //cleanup(machine)
    table = build_ptable("samples/commandlinegrammar", machine);
    synan (machine, table);
    fprintlistingfile(machine);
    fprinttokenfile(machine);
    printlistingfile(machine);
    fprint_ptable (&table);
    //printtokenfile(machine);
    cleanup(machine);
    return 0;
}
Пример #4
0
/*
 * Test the result for the bic calculator.
 */
int main(int argc, char** argv) {
  char** samples = read_lines(argv[1]);
  int depth = strtod(argv[2], NULL);
  

  setup_BIC(samples, depth, prob_root, bic_root);
  print_tree(prob_root, depth);
  printf("----------------\n");
  
//  print_tree(bic_root, "");

  printf("\nlogN=%f\n\n",logN);
  
  // int n = size_of_sample();
  get_T(prob_root);
  print_tree(prob_root, depth);
    

  Vec c = get_Tvec(prob_root);
  print_Vec(c);
  
  sort_Vec(c);
  uniquefy_Vec(c);
  print_Vec(c);
  for(int i = 0; i < c->len; i++)
      c->x[i] /= logN;
  print_Vec(c);
  Champion_item champs = champion_set_from_vec(c);
  
  ITERA(Champion_item, cs, champs, next) {
      pprint_Tau(cs->tau);
      printf("\n");
  }
Пример #5
0
static int do_connecting(void)
{
  struct key csession_secret;
  struct key csession_public;
  struct key tmpkey;
  unsigned backoff = 1;

  saw_seq_gap = 0;
  buffer->rewind();
  key_generate(&csession_secret, &csession_public, keyex);
  make_ini(&csession_public, buffer->peek());
  keylist_exchange_list_key(&tmpkey, &server_publics, &csession_secret);
  auth_start(&cid_authenticator, &tmpkey);

  while (!exitasap) {
    send_packet("INI1", cid_timeout * backoff);
    while (!exitasap) {
      if (poll_both() == 0)
	return STATE_DISCONNECTED;
      if (stdin_ready)
	read_lines();
      if (sock_ready) {
	if (receive_cid(&csession_secret))
	  return STATE_SENDING;
	backoff = 0;
      }
    }
    if (backoff < retransmits)
      ++backoff;
  }
  return STATE_EXITING;
}
Пример #6
0
// create a mesh storing a pointer in a map so it can be retrieved later by geometry UID
bool MeshImporter::write_geometry(const COLLADAFW::Geometry *geom)
{

	if (geom->getType() != COLLADAFW::Geometry::GEO_TYPE_MESH) {
		// TODO: report warning
		fprintf(stderr, "Mesh type %s is not supported\n", bc_geomTypeToStr(geom->getType()));
		return true;
	}
	
	COLLADAFW::Mesh *mesh = (COLLADAFW::Mesh *)geom;
	
	if (!is_nice_mesh(mesh)) {
		fprintf(stderr, "Ignoring mesh %s\n", bc_get_dae_name(mesh).c_str());
		return true;
	}
	
	const std::string& str_geom_id = mesh->getName().size() ? mesh->getName() : mesh->getOriginalId();
	Mesh *me = BKE_mesh_add(G.main, (char *)str_geom_id.c_str());
	me->id.us--; // is already 1 here, but will be set later in BKE_mesh_assign_object

	// store the Mesh pointer to link it later with an Object
	// mesh_geom_map needed to map mesh to its geometry name (for shape key naming)
	this->uid_mesh_map[mesh->getUniqueId()] = me;
	this->mesh_geom_map[std::string(me->id.name)] = str_geom_id;
	
	read_vertices(mesh, me);
	read_polys(mesh, me);
	BKE_mesh_calc_edges(me, false, false);

	// read_lines() must be called after the face edges have been generated.
	// Oterwise the loose edges will be silently deleted again.
	read_lines(mesh, me);
	return true;
}
Пример #7
0
static void fortran_prescanner_process(prescanner_t* prescanner)
{
	file_lines = NULL;
	last_line = file_lines;

	// Load all the file into memory
	read_lines(prescanner);

	// Cut lines to be of width 'prescanner.width'
	cut_lines(prescanner);

	// We used to remove comments here but it is better to convert them
	convert_whole_line_comments();

	// Join continuated lines
	join_continuated_lines(prescanner);

#if 0
	// Lines that were not appended any continuation line have not been trimmed
	// their inline comments
	remove_inlined_comments();
#endif

	convert_lines(prescanner);

	if (!prescanner->append)
	{
		continuate_lines(prescanner);
	}

	print_lines(prescanner);

    close_files(prescanner);
}
int main(void) 
{
  n_array t;
  int i, j, m;
  char *a, *vars;
  c_link op_stack;
  i_link num_stack;
  
  printf("Enter those lines:\n");
  t = read_lines();
  cSTACKinit();
  iSTACKinit();
  for (i = 0; i < t.n; i++)
    {
      a = t.arr[i];
      m = strlen(a);
      for (j = 0; j < m; j++)
	{
	    
	  
	}
    }
  /* printf("Enter the seize of stack: "); */
  /* scanf("%d", &n); */
  /* STACKinit(n); */
  /* STACKpush(1); */
  /* STACKpush(2); */
  /* printf("%d, %d\n", STACKpop(), STACKpop()); */
  /* printf("Stack empty? %d\n", STACKempty()); */
  return 0;
}
Пример #9
0
/* Move the buffer up and down in the file in order to scroll */
static void buffer_down(int nlines)
{
	cur_fline += nlines;
	read_lines();
	cap_cur_fline(nlines);
	buffer_fill_and_print();
}
Пример #10
0
static void buffer_up(int nlines)
{
	cur_fline -= nlines;
	if (cur_fline < 0) cur_fline = 0;
	read_lines();
	buffer_fill_and_print();
}
Пример #11
0
int main(int argc, char* argv[])
{
	// read first argument; must be a file path
	std::string filename = argv[1];

	// parse lines from filename into a dictionary mapping from int->word
	std::map<int, icu::UnicodeString> dict = read_lines(filename);

	UErrorCode success = U_ZERO_ERROR;
	icu::NumberFormat *nf = icu::NumberFormat::createInstance(success);
	// seems to run faster when not absolutely enforcing min/max fractional digits
	//nf->setMinimumFractionDigits(0);
    //nf->setMaximumFractionDigits(0);
    nf->setGroupingUsed(false);

	// display entire map using iterators
	for (std::map<int, icu::UnicodeString>::iterator it = dict.begin(); it != dict.end(); ++it) {
		//std::cout << it->first << ": " << it->second << std::endl;

		icu::UnicodeString temp_ustring;
		std::cout << nf->format(it->first, temp_ustring) << ": " << it->second << std::endl;
	}

	return 0;
}
Пример #12
0
int
read_file(std::vector<Alarm> &alarms)
{
	std::vector<std::string> lines;

	if (read_lines(lines) != 0) {
		return -1;
	}

	for (const std::string &str : lines) {
		Alarm alarm;

		if (alarm.read_file_str(str.c_str()) != 0) {
			return -1;
		}

		try {
			alarms.push_back(alarm);
		}
		catch (...) {
			fputs("Error: unable to allocate memory\n", stderr);
			return -1;
		}
	}

	return 0;
}
Пример #13
0
/* Gera o arquivo de saida */
void gera_csv_reduzido(char fnamein[], char fnameout[]) {
	FILE *in, *out;
	int n, *campos;
	int columns, lines;
	int i, j;
	char **values;
	
	/* Abrindo os arquivos de entrada e saida */
	in = fopen(fnamein, "r");
	out = fopen(fnameout, "w");
	
	/* Se nao conseguir abrir, retorna */
	if ((in == NULL) || (out == NULL)) {
		return;
	}
	
	/* Quantidade de colunas */
	columns = columns_file(in);
	
	/* Quantidade de linhas */
	lines = lines_file(in);
	
	/* Alocacao da matriz que armazenara os campos em cada linha */
	values = alloc_matrix(columns, MAX_CAMP);
	
	/* Quantidade de colunas que serao impressas no arquivo de saida */
	scanf("%d", &n);
	
	/* Alocacao do vetor que armazenara quais colunas serao impressas */
	campos = malloc(n * sizeof(int));
	
	/* Leitura dos numeros das colunas a serem impressas */
	for (i = 0; i < n; i++)
		scanf("%d", &campos[i]);
	
	/* Leitura das linhas do arquivo de entrada */
	for (i = 0; i < lines; i++) {
		read_lines(in, columns, values);
		
		/* Impressao dessas linhas no arquivo de saida */
		for (j = 0; j < n; j++) {
			fprintf(out, "%s", values[campos[j]-1]);
			if (j != n-1)
				fprintf(out, ",");
		}
		fprintf(out, "\n");
	}
	
	/* Fechando os arquivos abertos pelo programa */
	if (in)
		fclose(in);
	if (out)
		fclose(out);
	
	/* Liberando a memoria alocada pela matriz */
	free_matrix(values, columns);
}
Пример #14
0
static int read_file(char *filename, int quiet)
{
  verify(filename != NULL, "null arg filename");
  verify(filename[0] != '\0', "empty arg filename");

  if (verbose > 0)
    { fprintf(stderr, "%s: read_file(%s)\n", prog, filename); }

  static struct list_names filenames;	// file names come from -f and include
  static int init = 0;
  if (init == 0)
    { list_names_init(&filenames, "filenames"); init++; }

  if (verbose > 1)
    { list_names_print(&filenames); }

  // if (filename is on the list already) { return 1 }
  // else { put filename on the list and continue }
  if (list_names_append_if_new(&filenames, filename) == 1)
    { return 1; }

  if (verbose > 0)
    { list_names_print(&filenames); }

  if (strcmp(filename, "-") == 0)
    { read_lines("[stdin]", stdin); return 1; }

  FILE *fp = fopen(filename, "r");
  if (fp == NULL)
    {
      if (quiet == 0)
	fprintf(stderr, "%s: could not open input file %s: %s\n", prog, filename, strerror(errno));
      return 0;
    }

  read_lines(filename, fp);

  if (fclose(fp) != 0)
    {
      fprintf(stderr, "%s: could not close input file %s: %s\n", prog, filename, strerror(errno));
    }

  return 1;
}
Пример #15
0
int main()
{
        int line_count;
        char storage[MAXLINELENGTH * MAXLINECOUNT];
        char* lines[MAXLINECOUNT]; /* a list of pointers to locations in storage[] */

        line_count = read_lines(storage, lines);
        qsort(lines, 0, line_count);
        write_lines(lines, line_count);
        return 0;
}
Пример #16
0
int main(int argc, char** argv) {
    if(argc != 3) {
        std::fprintf(stderr, "usage: levelc [file]\n");
        return EXIT_FAILURE;
    }

    std::vector<grid_t> levels;

    char* const in_filename = argv[1];
    char* const out_filename = argv[2];
    std::vector<std::string> lines = read_lines(in_filename);
    std::reverse(lines.begin(), lines.end());
    int line_number = 1;

    while(!lines.empty() && lines.back().empty()) {
        lines.pop_back();
        ++line_number;
    }

    while(lines.size() >= H) {
        grid_t new_level;
        for(int i = 0; i != H; ++i, ++line_number) {
            if(lines.back().length() < W) {
                std::fprintf(stderr, "parse error; line %i too short\n", 
                             line_number);
                return EXIT_FAILURE;
            }
            std::copy(lines.back().begin(), lines.back().end(),
                      new_level[i].begin());
            lines.pop_back();
        }
        levels.push_back(new_level);

        while(!lines.empty() && lines.back().empty()) {
            lines.pop_back();
            ++line_number;
        }
    }

    if(lines.size() > 1) {
        std::fprintf(stderr, "incomplete level at end\n");
        return EXIT_FAILURE;
    }

    // Set this to true to make testing levels easier.
    constexpr bool reverse = 0;
    if(reverse)
        std::reverse(levels.begin(), levels.end());
    write_levels(out_filename, levels, reverse);

    std::printf("finished!\n");
}
int main(int argc, char* argv[])
{
    int num_lines;
    char* lines[MAX_NUM_LINES];

    bool sort_numerically = false;

    if (argc > 1)
    {
        for (int i = 1; i < argc; ++i)
        {
            if (strcmp(argv[i], SORT_NUMERICALLY) == 0)
            {
                sort_numerically = true;
            }
            else if (strcmp(argv[i], SORT_REVERSE) == 0)
            {
                sort_reverse = true;
            }
            else if (strcmp(argv[i], FOLD_CASE) == 0)
            {
                fold_case = true;
            }
            else if (strcmp(argv[i], SORT_BY_FIELD) == 0)
            {
                if (i == argc - 1)
                {
                    printf("error: when sorting by field, you must specify the field to sort by\n"
                           "example: ./exercise_5-16 -e 2\n");
                }
                else
                {
                    sort_by_field = true;
                    field = atoi(argv[++i]);
                }
            }
        }
    }

    if ((num_lines = read_lines(lines)) >= 0)
    {
        quick_sort((void**) lines, 0, num_lines - 1,
            (int(*)(void*, void*))(sort_numerically ? numeric_cmp : lexicographic_cmp));
        write_lines(lines, num_lines);
        return 0;
    }
    else
    {
        printf("error: input too large to sort\n");
        return 1;
    }
}
Пример #18
0
void
mux(mux_ctx_t ctx)
{
	/* init reader, we use prchunk here */
	ctx->rdr = init_prchunk(ctx->infd);
	/* main loop */
	while (fetch_lines(ctx)) {
		read_lines(ctx);
	}
	/* free prchunk resources */
	free_prchunk(ctx->rdr);
	return;
}
Пример #19
0
static void buffer_line(int linenum)
{
	if (linenum < 0)
		linenum = 0;
	cur_fline = linenum;
	read_lines();
	if (linenum + max_displayed_line > max_fline)
		linenum = max_fline - max_displayed_line + TILDES;
	if (linenum < 0)
		linenum = 0;
	cur_fline = linenum;
	buffer_fill_and_print();
}
double average_time(FILE *test, char *line_pointer_array[]) {
	double time_start, time_stop, time_total = 0.0;

	int element;
	for (element = 0; element < ITERATIONS_MAX; ++element) {
		time_start = (double)clock();
		read_lines(line_pointer_array, test);
		time_stop = (double)clock();
		time_total += time_stop - time_start;
	}

	return time_total;
}
Пример #21
0
int load_translate_table(char ***table, char *file, int nr_trans)
{
	SceUID fd;
	char linebuf[128];
	char *read_alloc_buf;
	int i;

	if (table == NULL) {
		return -1;
	}

	*table = NULL;

	linebuf[sizeof(linebuf)-1] = '\0';
	fd = sceIoOpen(file, PSP_O_RDONLY, 0);

	if(fd < 0) {
		return fd;
	}

	read_alloc_buf = vpl_alloc(READ_BUF_SIZE + 64);

	if(read_alloc_buf == NULL) {
		sceIoClose(fd);
		return -1;
	}

	read_buf = (void*)(((u32)read_alloc_buf & (~(64-1))) + 64);
	i = 0;

	while(i < nr_trans) {
		if (read_lines(fd, linebuf, sizeof(linebuf)-1) < 0) {
			break;
		}

//		printf("linebuf %s\n", linebuf);
		set_translate_table_item(table, linebuf, i, nr_trans);
		i++;
	}

	if (i < nr_trans) {
		sceIoClose(fd);
		vpl_free(read_alloc_buf);
		return -1;
	}

	sceIoClose(fd);
	vpl_free(read_alloc_buf);

	return 0;
}
Пример #22
0
static void open_file_and_read_lines(void)
{
	if (filename) {
		xmove_fd(xopen(filename, O_RDONLY), STDIN_FILENO);
	} else {
		/* "less" with no arguments in argv[] */
		/* For status line only */
		filename = xstrdup(bb_msg_standard_input);
	}
	readpos = 0;
	readeof = 0;
	last_line_pos = 0;
	terminated = 1;
	read_lines();
}
Пример #23
0
Файл: pr8.c Проект: njb5174/Hake
int pr8_read(char *file)
{
  if (file == NULL) return 0;

  printf("file: %s\n", file);
  
  static struct list_names * filenames = NULL;
  if (filenames == NULL) filenames = list_names_allocate("filenames");
    // by construction, filenames is now not NULL
    
    // if (file is on the list already) { return 1 }
  // else { put filename on the list and continue }
  if (list_names_append_if_new(filenames, file) == 1)
    { return 1; }
    
    if (strcmp(file, "-") == 0)
    { read_lines("[stdin]", stdin); return 1; }
    
    FILE *fp = fopen(file, "r");
    
    if (fp == NULL)
    {
//		fprintf(stderr, "%s: could not open input file %s: %s\n", prog, file, strerror(errno));
      return 0;
    }
    
    read_lines(file, fp);
    
    if (fclose(fp) != 0)
    {
      fprintf(stderr, "%s: could not close input file %s: %s\n", prog, file, strerror(errno));
    }

  return 1;

}
Пример #24
0
/*
 * Test the result for the bic calculator.
 */
int main(int argc, char** argv) {
  char** samples = read_lines(argv[1]);
  double c = strtod(argv[2], NULL);

  setup_BIC(samples, 5);

  Tau* tao = calculate_BIC(c);

  Tau_item* item = tao->item;
  while (item != NULL) {
    printf("%s ", item->string);
    item = item->next;
  }
  printf("\n");
}
Пример #25
0
int main()
{
	int nlines; /* Number of lines */
	char * plines[MAX_LINES]; /* Pointers to lines */
	
	if ((nlines = read_lines(plines, MAX_LINES)) < 0)
	{
		fprintf(stderr, "Error: Lack of memory. Input is too large.\n");
		return 1;
	}

	my_qsort(plines, 0, nlines-1);
	write_lines(plines, nlines);

	return 0;
}
Пример #26
0
Файл: zad3.c Проект: foo/ii
int main(int argc, char *argv[])
{
  if(argc != 3)
    {
      printf("usage: zad3.e m n\n");
      return -1;
    }

  sscanf(argv[1], "%d", &m);
  sscanf(argv[2], "%d", &n);
  
  struct List* lines = read_lines();
  lines = quicksort(lines);
  iterate(lines, print_str);
  iterate(lines, cleanup);
  return 0;
}
Пример #27
0
static void open_file_and_read_lines(void)
{
    if (filename) {
        int fd = xopen(filename, O_RDONLY);
        dup2(fd, 0);
        if (fd) close(fd);
    } else {
        /* "less" with no arguments in argv[] */
        /* For status line only */
        filename = xstrdup(bb_msg_standard_input);
    }
    readpos = 0;
    readeof = 0;
    linepos = 0;
    terminated = 1;
    read_lines();
}
Пример #28
0
static void goto_match(int match)
{
	if (!pattern_valid)
		return;
	if (match < 0)
		match = 0;
	/* Try to find next match if eof isn't reached yet */
	if (match >= num_matches && eof_error > 0) {
		wanted_match = match; /* "I want to read until I see N'th match" */
		read_lines();
	}
	if (num_matches) {
		normalize_match_pos(match);
		buffer_line(match_lines[match_pos]);
	} else {
		print_statusline("No matches found");
	}
}
Пример #29
0
unsigned char*
read_image (const char *filename, int *width, int *height)
{
    image_reader_t *reader = open_image_reading(filename);
    unsigned char *data;

    if (reader == 0)
	return 0;

    *width = reader->width;
    *height = reader->height;

    data = (unsigned char*)malloc(*width * *height * 3);

    read_lines(reader, data, *height);

    free_image_reader(reader);

    return data;
}
Пример #30
0
static ssize_t getch_nowait(char* input, int sz)
{
    ssize_t rd;
    struct pollfd pfd[2];

    pfd[0].fd = STDIN_FILENO;
    pfd[0].events = POLLIN;
    pfd[1].fd = kbd_fd;
    pfd[1].events = POLLIN;
again:
    tcsetattr(kbd_fd, TCSANOW, &term_less);
    /* NB: select/poll returns whenever read will not block. Therefore:
     * if eof is reached, select/poll will return immediately
     * because read will immediately return 0 bytes.
     * Even if select/poll says that input is available, read CAN block
     * (switch fd into O_NONBLOCK'ed mode to avoid it)
     */
    rd = 1;
    if (max_fline <= cur_fline + max_displayed_line
            && eof_error > 0 /* did NOT reach eof yet */
       ) {
        /* We are interested in stdin */
        rd = 0;
    }
    /* position cursor if line input is done */
    if (less_gets_pos >= 0)
        move_cursor(max_displayed_line + 2, less_gets_pos + 1);
    fflush(stdout);
    safe_poll(pfd + rd, 2 - rd, -1);

    input[0] = '\0';
    rd = safe_read(kbd_fd, input, sz); /* NB: kbd_fd is in O_NONBLOCK mode */
    if (rd < 0 && errno == EAGAIN) {
        /* No keyboard input -> we have input on stdin! */
        read_lines();
        buffer_fill_and_print();
        goto again;
    }
    set_tty_cooked();
    return rd;
}