move input to separate file

This commit is contained in:
Chris Cromer 2021-06-26 22:38:22 -04:00
parent 53e3c1e276
commit 907af65b94
3 changed files with 33 additions and 22 deletions

View File

@ -21,6 +21,7 @@
#include <sys/types.h>
#include <unistd.h>
#include "color.h"
#include "console_line.h"
/**
* Get the logged in user's username.
@ -57,3 +58,29 @@ void print_input_line() {
printf(BRIGHT_CYAN "%s" MAGENTA "@" RED "localhost" MAGENTA ":" BLUE "%s" MAGENTA "$ " RESET, name, cwd);
free(cwd);
}
char *get_console_input() {
size_t buffer_size = 0;
char *line = NULL;
if (getline(&line, &buffer_size, stdin) == -1) {
if (feof(stdin)) {
// the stdin was closed, this usually happens for CTRL-D
printf("\n");
if (line != NULL) {
free(line);
line = NULL;
}
exit(EXIT_SUCCESS);
}
else {
perror("getline() error: ");
if (line != NULL) {
free(line);
line = NULL;
}
exit(EXIT_FAILURE);
}
}
return line;
}

View File

@ -15,9 +15,13 @@
#ifndef _MYSHELLIN_CONSOLE_LINE
#define _MYSHELLIN_CONSOLE_LINE
#define CONSOLE_BUFFER_SIZE 1024
char *get_user();
char *get_working_directory();
void print_input_line();
char *get_console_input();
#endif

View File

@ -33,30 +33,10 @@ void remove_new_line(char* line) {
* This is the loop that checks for user input and acts on it.
*/
void loop() {
size_t buffer_size = 0;
char *line = NULL;
while (1) {
print_input_line();
if (getline(&line, &buffer_size, stdin) == -1) {
if (feof(stdin)) {
// the stdin was closed, this usually happens for CTRL-D
printf("\n");
if (line != NULL) {
free(line);
line = NULL;
}
exit(EXIT_SUCCESS);
}
else {
perror("getline() error: ");
if (line != NULL) {
free(line);
line = NULL;
}
exit(EXIT_FAILURE);
}
}
char *line = get_console_input();
remove_new_line(line);