Skip to content

Commit e038a18

Browse files
committed
Correct the return value of fputc function
According to the man page, the return value of fputc() should be either the character written as an "unsigned char" cast to an "int" or EOF on error, but the current implementation doesn't follow the specification. Therefore, these changes correct the implementation to return the ASCII code of the written character or -1 if the output fails, thereby matching the description in the man page. Additionally, the necessary test cases are also added to validate the correctness.
1 parent a603970 commit e038a18

File tree

6 files changed

+28
-7
lines changed

6 files changed

+28
-7
lines changed

lib/c.c

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -496,10 +496,10 @@ char *fgets(char *str, int n, FILE *stream)
496496

497497
int fputc(int c, FILE *stream)
498498
{
499-
char buf[1];
499+
int buf[2];
500500
buf[0] = c;
501-
__syscall(__syscall_write, stream, buf, 1);
502-
return 0;
501+
buf[1] = -1;
502+
return buf[__syscall(__syscall_write, stream, buf, 1) <= 0];
503503
}
504504

505505
/* Non-portable: Assume page size is 4KiB */

tests/driver.sh

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1611,4 +1611,25 @@ int main()
16111611
}
16121612
EOF
16131613

1614+
# test fputc()
1615+
try_output 0 "awritten = a" << EOF
1616+
int main()
1617+
{
1618+
FILE *f = 1;
1619+
int c = fputc('a', f);
1620+
printf("written = %c", c);
1621+
return 0;
1622+
}
1623+
EOF
1624+
1625+
try_output 1 "" << EOF
1626+
int main()
1627+
{
1628+
FILE *f = 1;
1629+
__syscall(__syscall_close, 1);
1630+
int c = fputc('a', f);
1631+
return c == -1;
1632+
}
1633+
EOF
1634+
16141635
echo OK

tests/snapshots/fib-arm.json

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

tests/snapshots/fib-riscv.json

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

tests/snapshots/hello-arm.json

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

tests/snapshots/hello-riscv.json

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)