Exemple #1
0
int main(int argc, char *argv[]) {

	/* Ensure proper usage */
	if (argc < 2) {
		fprintf(stdout, USAGEMSG);
		return EXIT_FAILURE;
	}

	if(isatty(fileno(stdin))) {
		uint32_t  opt;
		uint32_t limit;

		while((opt = getopt(argc, argv, "hf:e:t:")) != -1) {
			switch(opt) {
				case 'h':
					fprintf(stdout, USAGEMSG);
					exit(EXIT_SUCCESS);
				case 'f':
					if(!bf_readfile(optarg)) {
						exit(EXIT_FAILURE);
					}
					break;
				case 'e':
					bf_eval(optarg);
					break;
				case 't':
					limit = atoi(optarg);
					if (limit <= MAX_CELLS) {
						bf_showtape_range(0, limit);
					}
					else {
						fprintf(stderr, "The number of tape memory locations to be displayed should be between 0 and 65535.\n");
						exit(EXIT_FAILURE);
					}
					break;
				case '?':
					fprintf(stdout, "Please type bf -h for help.\n");
					break;
			}
		}
	}

	/* Write operations to pipe and evaluate */
	else {
		/* tape memory of size MAX_CELLS*/
		char* pipe = NULL;
		pipe = (char*) malloc(MAX_CELLS * sizeof(char));

		if(!fgets(pipe, MAX_CELLS, stdin)) {
			fprintf(stderr, "Unable to read into tape\n");
		}
		bf_eval(pipe);

		free(pipe);
	}

	return EXIT_SUCCESS;
}
Exemple #2
0
/* Read the file and pass it to the bf_eval() function */
void bf_readfile(char *filename) {
	FILE *file;
	//int c;
	//int pointer = 0;
	uint32_t size = 0;

	/* Get the size of the file */	
	file = fopen(filename, "r");
	if (file == NULL) {
		fprintf(stderr, "Error: Failed to open %s!\n", filename);
		exit(EXIT_FAILURE);
	}
	
	fseek(file, 0, SEEK_END);
	size = ftell(file);
	fseek(file, 0, SEEK_SET);

	/* Place each character from the file into the array */
	char* chars = NULL;
	chars = malloc((size + 1) * sizeof(*chars));
	if(!fread(chars, size, 1, file)) {
		fprintf(stderr, "Error: Unable to read %s\n", filename);
		exit(EXIT_FAILURE);
	}
	chars[size] = '\0';
	
	/* Close the file */
	fclose(file);

	/* Evaluate the code */
	bf_eval(chars);
}
Exemple #3
0
int main(int argc, char **argv)
{
	if (argc == 2)
		bf_eval(argv[1], ft_strlen(argv[1]));
	else
		write(1, "\n", 1);
	return 0;
}
Exemple #4
0
/* Read the file and pass it to the bf_eval() function.
 * Update: Now this function read dynamic and filter the input.
 *         Return 1 on success, and 0 on error.
 */
int bf_readfile(char *filename) {
	size_t n = 0, sz = 4;
	char* chars = malloc(sz);
	if(chars == NULL) {
		perror("Can't allocate memory");
		return 0;
	}

	FILE* f = fopen(filename, "r");
	if(f == NULL) {
		free(chars);
		perror("Can't open file");
		return 0;
	}

	char c, *r = NULL;
	while((c = fgetc(f)) != EOF) {
		if((r = strchr("<>+-[].,", c))) {
			if(n == sz) {
				sz *= 2;
				void* t = realloc(chars, sz);
				if(t == NULL) {
					free(chars);
					fclose(f);
					perror("Error allocating memory");
					return 0;
				}
				chars = t;
			}
			chars[n++] = *r;
		}
	}
	fclose(f);

	bf_eval(chars);
	free(chars);

	return 1;
}