Skip to content

Commit

Permalink
Merge pull request #99 from shinh/gets-again
Browse files Browse the repository at this point in the history
Fix fgets implementation again
  • Loading branch information
shinh authored Feb 13, 2021
2 parents c30d33f + a50477b commit 18b45bc
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
6 changes: 4 additions & 2 deletions libc/stdio.h
Original file line number Diff line number Diff line change
Expand Up @@ -207,8 +207,10 @@ char* fgets(char* s, int size, FILE* fp) {
int i = 0;
while (i < size - 1) {
int c = fgetc(fp);
if (c == EOF)
break;
if (c == EOF) {
if (i) break;
return NULL;
}
s[i++] = c;
if (c == '\n')
break;
Expand Down
28 changes: 22 additions & 6 deletions test/fgets.c
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,29 @@

int main() {
char buf[256];
char* ptr = fgets(buf, 100, stdin);
printf("%d\n", ptr == buf);
printf("%s\n", ptr);
char* ptr;

ptr = fgets(buf, 100, stdin);
printf("%d\n", ptr == buf);
printf("%s\n", ptr);
printf("%d %s\n", ptr == buf, ptr);

ptr = fgets(buf, 100, stdin);
printf("%d\n", ptr == 0);
printf("%d %s\n", ptr == buf, ptr);

buf[0] = 'a';
ptr = fgets(buf, 100, stdin);
printf("%d %d\n", ptr == 0, buf[0]);

buf[0] = 'b';
ptr = fgets(buf, 1, stdin);
printf("%d %d\n", ptr == 0, buf[0]);

buf[0] = 'c';
ptr = fgets(buf, 100, stdin);
printf("%d %d\n", ptr == 0, buf[0]);

buf[0] = 'd';
ptr = fgets(buf, 0, stdin);
printf("%d %d\n", ptr == 0, buf[0]);

return 0;
}

0 comments on commit 18b45bc

Please sign in to comment.