-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsimulate_gets.c
More file actions
37 lines (34 loc) · 889 Bytes
/
simulate_gets.c
File metadata and controls
37 lines (34 loc) · 889 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <stdio.h>
#include <string.h>
#define LINE_MAX 15
char buf[LINE_MAX];
int ch;
char *p;
/* Get a line of data from stdin. Behaves like gets()
in that the trailing newline is replaced with a null byte,
but this implementation puts a limit on the amount of data that can
be read, and it flushes the rest of the line out of stdin
if the line does not fit in the destination buffer. */
int main(void) {
if (fgets(buf, sizeof(buf), stdin)) {
/* fgets succeeds, scan for newline character */
p = strchr(buf, '\n');
if (p) {
*p = '\0';
}
else {
/* newline not found, flush stdin to end of line */
while (((ch = getchar()) != '\n')
&& !feof(stdin)
&& !ferror(stdin)
); // end while loop
}
}
else {
/* fgets failed, handle error */
puts("fgets failed. An empty file may have been provided");
return 1;
}
printf("%s\n", buf);
return 0;
}