1 | // ========================================================= // |
---|
2 | // // |
---|
3 | // File : gets_noOverflow.h // |
---|
4 | // Purpose : drop-in replacement for gets() // |
---|
5 | // // |
---|
6 | // Coded by Ralf Westram (coder@reallysoft.de) in Aug 23 // |
---|
7 | // http://www.arb-home.de/ // |
---|
8 | // // |
---|
9 | // ========================================================= // |
---|
10 | |
---|
11 | #ifndef GETS_NOOVERFLOW_H |
---|
12 | #define GETS_NOOVERFLOW_H |
---|
13 | |
---|
14 | #ifndef _STDIO_H |
---|
15 | #include <stdio.h> |
---|
16 | #endif |
---|
17 | #ifndef _STRING_H |
---|
18 | #include <string.h> |
---|
19 | #endif |
---|
20 | |
---|
21 | // inspired by https://codereview.stackexchange.com/questions/163133/c-gets-s-implementation |
---|
22 | |
---|
23 | |
---|
24 | #ifndef __cplusplus |
---|
25 | static |
---|
26 | #endif |
---|
27 | |
---|
28 | inline char *gets_noOverflow(char *buffer, int buffersize) { |
---|
29 | // behaves like gets(), but does NOT overflow the given 'buffer'. |
---|
30 | // 'buffersize' includes the terminal zero byte. |
---|
31 | // |
---|
32 | // Note: behavior of code may change, because the result is truncated |
---|
33 | // in those cases where an overflow did happen with gets()! |
---|
34 | |
---|
35 | char *result = fgets(buffer, buffersize, stdin); |
---|
36 | |
---|
37 | if (!result) { |
---|
38 | buffer[0] = 0; |
---|
39 | } |
---|
40 | else { |
---|
41 | char *delim = strchr(buffer, 0); |
---|
42 | if (delim>result) { |
---|
43 | char *last_read = delim-1; |
---|
44 | if (last_read[0] == '\n') { |
---|
45 | last_read[0] = 0; // remove trailing newline (as gets did) |
---|
46 | } |
---|
47 | else { |
---|
48 | int c = fgetc(stdin); |
---|
49 | if (c != EOF && c != '\n') { |
---|
50 | // original gets() did overflow buffer NOW! |
---|
51 | // continue reading as far as gets() would have done: |
---|
52 | do c = fgetc(stdin); |
---|
53 | while (c != EOF && c != '\n'); |
---|
54 | } |
---|
55 | } |
---|
56 | } |
---|
57 | } |
---|
58 | |
---|
59 | return result; |
---|
60 | } |
---|
61 | |
---|
62 | #else |
---|
63 | #error gets_noOverflow.h included twice |
---|
64 | #endif // GETS_NOOVERFLOW_H |
---|