aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/linebuffer.c1
-rw-r--r--src/main.c5
-rw-r--r--src/word.c37
-rw-r--r--src/word.h9
4 files changed, 36 insertions, 16 deletions
diff --git a/src/linebuffer.c b/src/linebuffer.c
index 14592ef..1b9c1f1 100644
--- a/src/linebuffer.c
+++ b/src/linebuffer.c
@@ -1,4 +1,5 @@
#include "linebuffer.h"
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
diff --git a/src/main.c b/src/main.c
index 9d8e5b4..5fdc535 100644
--- a/src/main.c
+++ b/src/main.c
@@ -1,9 +1,10 @@
-#include "linebuffer.h"
-#include "word.h"
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
+#include "linebuffer.h"
+#include "word.h"
+
#define MAX_WORD_LENGTH 20
int main(void) {
diff --git a/src/word.c b/src/word.c
index 4b2249b..87643d6 100644
--- a/src/word.c
+++ b/src/word.c
@@ -1,28 +1,37 @@
#include "word.h"
-static int read_char(FILE *fp);
+#include <ctype.h>
int read_word(FILE *fp, char *word, size_t length) {
+ if (fp == NULL || word == NULL) {
+ return READ_WORD_ERR_READ;
+ }
+
int ch;
size_t position = 0;
- while ((ch = read_char(fp)) == ' ')
+ while (isspace(ch = getc(fp)))
;
- while (ch != ' ' && ch != EOF) {
- if (position < length) {
- word[position++] = ch;
+ while (!isspace(ch) && ch != EOF) {
+ if (position >= length - 1) {
+ // Note: -1 to ensure we have space for the null terminator
+ // Once we hit the end of our available space, we stop reading,
+ // even if we didn't read the whole word.
+ break;
}
- ch = read_char(fp);
+ word[position++] = ch;
+ ch = getc(fp);
+ }
+ if (length >= 0) {
+ word[position] = '\0';
}
- word[position] = '\0';
- return ch;
-}
-static inline int read_char(FILE *fp) {
- int ch = getc(fp);
- if (ch == '\n' || ch == '\t') {
- return ' ';
+ if (ferror(fp)) {
+ return READ_WORD_ERR_READ;
+ }
+ if (position == 0 && ch == EOF) {
+ return READ_WORD_ERR_EOF;
}
- return ch;
+ return READ_WORD_SUCCESS;
}
diff --git a/src/word.h b/src/word.h
index 327116e..b5d94b5 100644
--- a/src/word.h
+++ b/src/word.h
@@ -3,9 +3,16 @@
#include <stdio.h>
+#define READ_WORD_ERR_READ -1
+#define READ_WORD_ERR_EOF 0
+#define READ_WORD_SUCCESS 1
+
/**
* Read in a word from a file up to size length.
*
+ * If there is any leading whitespace, it will be discarded
+ * before starting to read in a word.
+ *
* @param[in] fp The file to read a word from.
* @param[out] word The word that was read as a null-terminated string.
* @param[in] length The length of the word to read in.
@@ -13,6 +20,8 @@
* @note `length` should be the number of characters you'd
* like to read in plus one to take into account the
* null terminator.
+ *
+ * @returns < 0 on read error; 0 on EOF; > 0 on success.
*/
int read_word(FILE *fp, char *word, size_t length);