init: code du lecteur de stdin
This commit is contained in:
commit
5a0ce6d53c
3 changed files with 46 additions and 0 deletions
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
||||||
|
/out
|
9
Makefile
Normal file
9
Makefile
Normal file
|
@ -0,0 +1,9 @@
|
||||||
|
.PHONY: all clean
|
||||||
|
|
||||||
|
all: out out/sh
|
||||||
|
|
||||||
|
out:
|
||||||
|
mkdir -p -- $@
|
||||||
|
|
||||||
|
out/sh: $(wildcard src/*.c)
|
||||||
|
cc -g -Wall -Wextra -Werror -ansi -o $@ $^
|
36
src/main.c
Normal file
36
src/main.c
Normal file
|
@ -0,0 +1,36 @@
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
size_t buffer_size;
|
||||||
|
size_t initial_buffer_size = 64;
|
||||||
|
char *input_buffer;
|
||||||
|
char *initial_buffer_position;
|
||||||
|
unsigned int how_many_characters_to_read;
|
||||||
|
|
||||||
|
while (1) {
|
||||||
|
buffer_size = initial_buffer_size;
|
||||||
|
how_many_characters_to_read = buffer_size + 1;
|
||||||
|
input_buffer = malloc(how_many_characters_to_read);
|
||||||
|
initial_buffer_position = input_buffer;
|
||||||
|
|
||||||
|
printf("shell> ");
|
||||||
|
while (fgets(input_buffer, how_many_characters_to_read, stdin) != NULL &&
|
||||||
|
input_buffer[strlen(input_buffer) - 1] != '\n') {
|
||||||
|
size_t new_buffer_size = buffer_size * 2;
|
||||||
|
if (buffer_size != initial_buffer_size) {
|
||||||
|
how_many_characters_to_read = buffer_size + 1;
|
||||||
|
}
|
||||||
|
input_buffer = realloc(initial_buffer_position, new_buffer_size + 1);
|
||||||
|
initial_buffer_position = input_buffer;
|
||||||
|
input_buffer += buffer_size;
|
||||||
|
buffer_size = new_buffer_size;
|
||||||
|
}
|
||||||
|
input_buffer = initial_buffer_position;
|
||||||
|
|
||||||
|
printf("%s", input_buffer);
|
||||||
|
|
||||||
|
free(input_buffer);
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue