From b3ed9cf16022c1e9f63439f8c41004289579f806 Mon Sep 17 00:00:00 2001 From: John Schneiderman Date: Sun, 22 Sep 2024 12:26:46 +0200 Subject: [PATCH] Adds implementation of the get_s C function. --- include/stdio.c | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ include/stdio.h | 2 ++ 2 files changed, 50 insertions(+) diff --git a/include/stdio.c b/include/stdio.c index a806adb..60f995e 100644 --- a/include/stdio.c +++ b/include/stdio.c @@ -1,6 +1,7 @@ #include "stdio.h" #include "conio.h" #include "stdlib.h" +#include "stdbool.h" #if defined(__C128__) #pragma code(lowcode) @@ -236,6 +237,53 @@ char * gets(char * str) return str; } +char* gets_s(char* str, size_t n) +{ + if (str == NULL) + return NULL; + + if (n == 0 || n == 1) + return NULL; + str[0] = '\0'; + size_t leftToStore = n - 1; + bool isTruncated = false; + + __asm { + ldy #0 + + read_loop: + jsr getpch + + // Check if the read in character is the line feed. + cmp #10 + beq read_done + + // Check to see if the maximum characters is reached. + ldx leftToStore + cpx #0 + beq read_max + + // Store the read in character & prepare for the next read. + sta (str), Y + iny + dec leftToStore + jmp read_loop + + read_max: + ldx #1 + stx isTruncated + + read_done: + // Place a null character at the end of the C-string. + lda #0 + sta (str), Y + } + + if (isTruncated) + return NULL; + return str; +} + typedef void * (* putstrfn)(void * handle, const char * str); void * putstrio(void * handle, const char * str) diff --git a/include/stdio.h b/include/stdio.h index 21c8167..a994351 100644 --- a/include/stdio.h +++ b/include/stdio.h @@ -1,6 +1,7 @@ #ifndef STDIO_H #define STDIO_H +#include #include @@ -11,6 +12,7 @@ char getchar(void); void puts(const char * str); char * gets(char * str); +char* gets_s(char* str, size_t n); void printf(const char * fmt, ...);