readwords/readwords.c
2021-05-29 12:21:57 +02:00

61 lines
1.7 KiB
C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_CHARS_PER_LINE 100
extern FILE *stdin;
char *myfgets(char *s, int size, FILE *stream) {
int cnt = 0;
memset(s, 0, size);
while (1) {
printf("cnt: %d\n", cnt);
int i = fgetc(stream);
if ((i >= 0) && (cnt < size)) {
s[cnt] = i;
}
cnt += 1;
if ((i == '\r') || (i == '\n')) {
s[cnt] = 0;
break;
}
}
return s;
}
void readwords() {
while (1) {
char *buf = malloc(MAX_CHARS_PER_LINE
+ 1 // one too many, to recognize too to many chars per line
+ 2 // CRLF
+ 1); // terminated null
if (myfgets(buf, MAX_CHARS_PER_LINE + 1, stdin)) { // one more for CRLF
if ((buf[strlen(buf)-1] == '\n') || (buf[strlen(buf)-1] == '\r')) {
buf[strlen(buf)-1] = 0;
printf("strip CR or LF\n");
}
if ((buf[strlen(buf)-1] == '\n') || (buf[strlen(buf)-1] == '\r')) {
buf[strlen(buf)-1] = 0;
printf("strip CR or LF\n");
}
printf("read a line\n");
printf("<%s>\n", buf);
printf("strlen: %ld\n", strlen(buf));
if (strlen(buf) == 0) {
printf("empty line, to be ignored or to end input\n");
break;
}
if (strlen(buf) > MAX_CHARS_PER_LINE) {
printf("too many chars per line, error\n");
fflush(stdin); // skip all overflowing chars instead of postponing them to the next fgets call
}
} else {
printf("fgets returns null\n");
}
}
}