add user name printing and newline stripping

This commit is contained in:
Chris Cromer 2021-06-19 20:05:20 -04:00
parent cc74038008
commit 93ace63885
5 changed files with 39 additions and 3 deletions

View File

@ -2,7 +2,7 @@ CC=clang
CFLAGS=-Wall -Isrc/include -DDEBUG -g -std=c17
LDFLAGS=
FILENAME=myshellin
SRC=src/myshellin.c src/loop.c
SRC=src/myshellin.c src/loop.c src/user.c
OBJ=$(SRC:.c=.o)
all: myshellin

View File

@ -1,2 +1,3 @@
void remove_new_line(char *line);
void print_input_line();
void loop();

1
src/include/user.h Normal file
View File

@ -0,0 +1 @@
char *get_user();

View File

@ -1,10 +1,18 @@
#define _GNU_SOURCE
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include "user.h"
void remove_new_line(char* line) {
line[strcspn(line, "\n")] = 0;
}
void print_input_line() {
printf("$ ");
char *name = get_user();
printf("%s $ ", name);
}
void loop() {
@ -13,6 +21,23 @@ void loop() {
while (1) {
print_input_line();
getline(&line, &buffer_size, stdin);
if (getline(&line, &buffer_size, stdin) == -1) {
if (feof(stdin)) {
// the stdin was closed, this usually happens for CTRL-D
printf("\n");
exit(EXIT_SUCCESS);
}
else {
perror("Error: ");
printf("\n");
exit(EXIT_FAILURE);
}
}
remove_new_line(line);
if (strcmp(line, "quit") == 0) {
break;
}
}
}

9
src/user.c Normal file
View File

@ -0,0 +1,9 @@
#include <pwd.h>
#include <stdio.h>
#include <unistd.h>
char *get_user() {
struct passwd *pass;
pass = getpwuid(getuid());
return pass->pw_name;
}