Browse Source

basic repl loop working

master
alistair 5 years ago
parent
commit
d2e9a4249e
  1. 3
      error.h
  2. 91
      main.c

3
error.h

@ -5,7 +5,8 @@ @@ -5,7 +5,8 @@
enum ExitCodes {
ER_SUCCESS,
ER_FAILURE,
ER_FAIL_TO_FORK
ER_FAIL_TO_FORK,
ER_ALLOC
};
#endif

91
main.c

@ -1,43 +1,106 @@ @@ -1,43 +1,106 @@
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include "error.h"
#include "run.h"
#define INITIALLINEBUFFER 80
#define INITIAL_WORD_SIZE 80
char *readline(FILE* in) {
int readline(FILE* in, char **out) {
int size_of_buffer = INITIALLINEBUFFER;
char *buffer = calloc(size_of_buffer, sizeof(char));
char character;
int count;
int count = 0;
while (true) {
if (count == (size_of_buffer)) {
buffer = reallocarray(buffer, (size_of_buffer *= 2), sizeof(char));
if (!buffer) {
return 0;
}
}
character = fgetc(in);
if (character == EOF || character == '\n') {
if (character == EOF) {
buffer[count] = '\0';
*out = buffer;
return EOF;
}
if (character == '\n') {
buffer[count] = '\0';
return buffer;
*out = buffer;
return ER_SUCCESS;
} else {
if (count == (size_of_buffer - 3)) {
buffer = reallocarray(buffer, (size_of_buffer *= 2),
sizeof(char));
if (!buffer) {
return ER_ALLOC;
}
}
buffer[count] = character;
count++;
}
}
}
int split_string(char **sep_string[], int *num, char *string, char delim) {
char **word_list = calloc(10, sizeof(char*));
int word_size;
char *word = calloc((word_size=INITIAL_WORD_SIZE), sizeof(char));
int num_words = 0;
int word_length = 0;
for (int i = 0; true; i++) {
if (string[i] == '\0') {
if (word_length) {
word_list[num_words] = word;
num_words++;
}
*sep_string = word_list;
*num = num_words;
return ER_SUCCESS;
}
if (string[i] == delim) {
if (word_length) {
word_list[num_words] = word;
num_words++;
word_length = 0;
word = calloc((word_size=INITIAL_WORD_SIZE), sizeof(char));
}
} else {
word[word_length] = string[i];
word_length++;
if (word_length == word_size - 2) {
word = reallocarray(word, word_size *= 2, sizeof(char));
}
}
}
return ER_FAILURE;
}
int repl(void) {
while (true) {
char *line;
printf("$ ");
if (readline(stdin, &line)) {
return ER_SUCCESS;
}
char **sep_string;
int num_words;
split_string(&sep_string, &num_words, line, ' ');
execute(stdin, stdout, sep_string);
for (int i = 0; i < num_words; i++) {
free(sep_string[i]);
}
free(sep_string);
free(line);
}
}

Loading…
Cancel
Save